@Test
 public void correctlyRecordsMetricsForFailedDeferredResultResponse() throws Exception {
   AnnotationConfigApplicationContext context =
       new AnnotationConfigApplicationContext(Config.class, MetricFilterAutoConfiguration.class);
   MetricsFilter filter = context.getBean(MetricsFilter.class);
   CountDownLatch latch = new CountDownLatch(1);
   MockMvc mvc =
       MockMvcBuilders.standaloneSetup(new MetricFilterTestController(latch))
           .addFilter(filter)
           .build();
   String attributeName = MetricsFilter.class.getName() + ".StopWatch";
   MvcResult result =
       mvc.perform(post("/createFailure"))
           .andExpect(status().isOk())
           .andExpect(request().asyncStarted())
           .andExpect(request().attribute(attributeName, is(notNullValue())))
           .andReturn();
   latch.countDown();
   try {
     mvc.perform(asyncDispatch(result));
     fail();
   } catch (Exception ex) {
     assertThat(result.getRequest().getAttribute(attributeName)).isNull();
     verify(context.getBean(CounterService.class)).increment("status.500.createFailure");
   } finally {
     context.close();
   }
 }
  public static AnnotationConfigApplicationContext inititializeApplicationContext() {
    final AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    ctx.register(PersistenceJPAConfig.class);
    ctx.refresh();

    return ctx;
  }
Пример #3
0
  public static void main(String[] args) {

    try (AnnotationConfigApplicationContext ctx =
        new AnnotationConfigApplicationContext("ch.rasc.mongodb.geolite")) {
      Datastore datastore = ctx.getBean(Datastore.class);

      // long myIp = 16777216l * 188 + 65536l * 61 + 256l * 140l + 26;
      long firstIp = 16777217; // first document
      long lastIp = 3758095359l; // last document
      long testIp = 1275328930;

      // first document
      System.out.print("First document: ");
      // Warmup
      findFast(datastore, firstIp);
      findFast(datastore, firstIp);

      // last document
      System.out.print("Last document: ");
      findFast(datastore, lastIp);

      // test document
      System.out.print("Test document: ");
      findFast(datastore, testIp);
    }
  }
 @Override
 protected ApplicationContext initApplicationContext() {
   AnnotationConfigApplicationContext wac = new AnnotationConfigApplicationContext();
   wac.register(WebConfig.class);
   wac.refresh();
   return wac;
 }
 @Test
 public void hazelcastCacheWithMainHazelcastAutoConfigurationAndSeparateCacheConfig()
     throws IOException {
   String mainConfig = "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml";
   String cacheConfig = "org/springframework/boot/autoconfigure/cache/hazelcast-specific.xml";
   AnnotationConfigApplicationContext applicationContext =
       new AnnotationConfigApplicationContext();
   EnvironmentTestUtils.addEnvironment(
       applicationContext,
       "spring.cache.type=hazelcast",
       "spring.cache.hazelcast.config=" + cacheConfig,
       "spring.hazelcast.config=" + mainConfig);
   applicationContext.register(DefaultCacheConfiguration.class);
   applicationContext.register(HazelcastAndCacheConfiguration.class);
   applicationContext.refresh();
   this.context = applicationContext;
   HazelcastInstance hazelcastInstance = this.context.getBean(HazelcastInstance.class);
   HazelcastCacheManager cacheManager = validateCacheManager(HazelcastCacheManager.class);
   HazelcastInstance cacheHazelcastInstance = getHazelcastInstance(cacheManager);
   assertThat(cacheHazelcastInstance, not(hazelcastInstance)); // Our custom
   assertThat(
       hazelcastInstance.getConfig().getConfigurationFile(),
       equalTo(new ClassPathResource(mainConfig).getFile()));
   assertThat(
       cacheHazelcastInstance.getConfig().getConfigurationFile(),
       equalTo(new ClassPathResource(cacheConfig).getFile()));
 }
Пример #6
0
 @Test
 public void simple() {
   AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);
   Hello h = ac.getBean(Hello.class);
   h.sayHello();
   assertThat(h.getHello(), is("Hello Toby"));
 }
 @Test
 public void oneTrueOneFalse() throws Exception {
   AnnotationConfigApplicationContext context =
       load(Config.class, "security.basic.enabled:false", "security.oauth2");
   assertThat(context.containsBean("myBean"), equalTo(false));
   context.close();
 }
  public static void main(String args[]) throws Throwable {

    AnnotationConfigApplicationContext applicationContext =
        new AnnotationConfigApplicationContext(
            RedisCachingConfiguration.class.getPackage().getName());

    Log log = LogFactory.getLog(Main.class);

    CustomerService customerService = applicationContext.getBean(CustomerService.class);

    Customer customer = customerService.createCustomer("Redis", "Lover");

    for (int i = 0; i < 10; i++) {
      Customer retrievedCustomer = customerService.getCustomerById(customer.getId());
      log.info(
          String.format(
              "customer.id (%s) == retreivedCustomer.id (%s)?  %s",
              customer.getId(),
              retrievedCustomer.getId(),
              customer.getId().equals(retrievedCustomer.getId())));
    }

    Customer updatedCustomer = customerService.updateCustomer(customer.getId(), "JPA", "Lover");

    log.info(String.format("updated customer's firstName: %s", updatedCustomer.getFirstName()));
  }
  public static void main(String[] args) throws Exception {

    SimpleDateFormat sdfByYYYYMMDD2 = new SimpleDateFormat("yyyy/MM/dd");

    EquityPriceInrangeCheck check = new EquityPriceInrangeCheck();

    Date date;
    if (args.length == 0) {
      date = new Date();
    } else {
      date = sdfByYYYYMMDD2.parse(args[1]);
    }

    date = sdfByYYYYMMDD2.parse("2013/11/20");

    AnnotationConfigApplicationContext ctx =
        new AnnotationConfigApplicationContext(AppConfig.class);

    RuleMappingService ruleMappingService = ctx.getBean(RuleMappingService.class);

    List<RuleMapping> ruleMappingList = ruleMappingService.getList(new RuleMapping());
    Map<String, RuleMapping> ruleMappingMap = new HashMap<String, RuleMapping>();
    for (int i = 0; i < ruleMappingList.size(); i++) {
      ruleMappingMap.put(ruleMappingList.get(i).getRuleKey(), ruleMappingList.get(i));
    }

    check.ruleCheck(ruleMappingMap, date, 11, "Y", 2);
  }
Пример #10
0
  public static void main(String... args)
      throws ExecutionException, TimeoutException, InterruptedException {
    AnnotationConfigApplicationContext ctx =
        new AnnotationConfigApplicationContext(AppConfig.class);
    TaskService taskService = ctx.getBean(TaskService.class);

    Workspace workspace = new Workspace();

    workspace.addParam("executable", "ls");
    workspace.addParam("arg1", "-lisa");

    Job job = new Job();
    job.setType("PROCESS");
    job.setWorkspace(workspace);

    try {
      final Future<Result> resultFuture = taskService.run(job);
      final Result result = resultFuture.get(10, TimeUnit.SECONDS);

      System.out.println("Result success = " + result.isSuccess());
      System.out.println("Result message = " + result.getMessage());
    } catch (Exception e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    }

    // Wait to exit.
    Thread.sleep(2000);
    ctx.destroy();
  }
  @Test
  public void testStateEvents() {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);
    assertTrue(ctx.containsBean(StateMachineSystemConstants.DEFAULT_ID_STATEMACHINE));
    @SuppressWarnings("unchecked")
    EnumStateMachine<TestStates, TestEvents> machine =
        ctx.getBean(StateMachineSystemConstants.DEFAULT_ID_STATEMACHINE, EnumStateMachine.class);

    TestStateMachineListener listener = new TestStateMachineListener();
    machine.addStateListener(listener);

    assertThat(machine, notNullValue());
    machine.sendEvent(MessageBuilder.withPayload(TestEvents.E1).setHeader("foo", "jee1").build());
    assertThat(listener.states.size(), is(1));
    assertThat(listener.states.get(0).from.getId(), is(TestStates.S1));
    assertThat(listener.states.get(0).to.getId(), is(TestStates.S2));
    machine.sendEvent(MessageBuilder.withPayload(TestEvents.E2).setHeader("foo", "jee2").build());
    assertThat(listener.states.size(), is(2));
    assertThat(listener.states.get(1).from.getId(), is(TestStates.S2));
    assertThat(listener.states.get(1).to.getId(), is(TestStates.S3));
    machine.sendEvent(MessageBuilder.withPayload(TestEvents.E4).setHeader("foo", "jee2").build());
    assertThat(listener.states.size(), is(2));

    ctx.close();
  }
  @Override
  public void configure(AtmosphereConfig config) {
    try {

      String s = config.getInitParameter(ATMOSPHERE_SPRING_EXCLUDE_CLASSES);
      if (s != null) {
        String[] list = s.split(",");
        for (String clazz : list) {
          excludedFromInjection.add(IOUtils.loadClass(getClass(), clazz));
        }

        if (list.length > 0) {
          preventSpringInjection = true;
        }
      }

      context = new AnnotationConfigApplicationContext();
      context.setParent(
          WebApplicationContextUtils.getWebApplicationContext(
              config.framework().getServletContext()));

      context.refresh();

      // Hack to make it injectable
      context.register(AtmosphereConfig.class);
      ((AtmosphereConfig)
              context.getBean(AtmosphereConfig.class.getCanonicalName(), config.framework()))
          .populate(config);
    } catch (Exception ex) {
      logger.warn("Unable to configure injection", ex);
    }
  }
 @Test
 public void enableRabbitAutomatically() throws Exception {
   load(NoEnableRabbitConfiguration.class);
   AnnotationConfigApplicationContext ctx = this.context;
   ctx.getBean(RabbitListenerConfigUtils.RABBIT_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME);
   ctx.getBean(RabbitListenerConfigUtils.RABBIT_LISTENER_ENDPOINT_REGISTRY_BEAN_NAME);
 }
 private AnnotationConfigApplicationContext load(Class<?> config, String... env) {
   AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
   EnvironmentTestUtils.addEnvironment(context, env);
   context.register(config);
   context.refresh();
   return context;
 }
  public void performAction() {
    /* Choose appropriate Spring profile */
    final String profileName = action.getSpringProfileName();

    /* Let action do any pre-setup work */
    action.beforeApplicationContextInit();

    /* Initialise ApplicationConetext */
    logger.debug("Setting up Spring ApplicationContext using profile '{}'", profileName);
    final AnnotationConfigApplicationContext applicationContext =
        new AnnotationConfigApplicationContext();
    applicationContext.getEnvironment().setActiveProfiles(profileName);
    QtiWorksApplicationContextHelper.registerConfigPropertySources(
        applicationContext, deploymentPropertiesResource);
    applicationContext.register(
        PropertiesConfiguration.class,
        JpaProductionConfiguration.class,
        JpaBootstrapConfiguration.class,
        ServicesConfiguration.class,
        ManagerConfiguration.class);
    applicationContext.refresh();

    /* Now let action class do its work*/
    try {
      action.run(applicationContext, actionParameters);
    } catch (final Exception e) {
      logger.warn("Unexpected Exception performing action", e);
    } finally {
      applicationContext.close();
    }
  }
Пример #16
0
 @Test
 public void testImportXmlWithAutowiredConfig() {
   AnnotationConfigApplicationContext ctx =
       new AnnotationConfigApplicationContext(ImportXmlAutowiredConfig.class);
   String name = ctx.getBean("xmlBeanName", String.class);
   assertThat(name, equalTo("xml.declared"));
 }
 @Before
 public void beforeTests() {
   DbHelper.clearDb();
   AnnotationConfigApplicationContext ctx =
       new AnnotationConfigApplicationContext(AppConfig.class);
   addressDao = ctx.getBean(AddressDao.class);
 }
Пример #18
0
 @Test
 public void testImportXmlWithNamespaceConfig() {
   AnnotationConfigApplicationContext ctx =
       new AnnotationConfigApplicationContext(ImportXmlWithAopNamespaceConfig.class);
   Object bean = ctx.getBean("proxiedXmlBean");
   assertTrue(AopUtils.isAopProxy(bean));
 }
 @Test
 public void basicBinding() {
   EnvironmentTestUtils.addEnvironment(context, "eureka.instance.appGroupName=mygroup");
   context.register(PropertyPlaceholderAutoConfiguration.class, TestConfiguration.class);
   context.refresh();
   assertEquals("mygroup", context.getBean(EurekaInstanceConfigBean.class).getAppGroupName());
 }
 @Test
 public void skipsFilterIfMissingServices() throws Exception {
   AnnotationConfigApplicationContext context =
       new AnnotationConfigApplicationContext(MetricFilterAutoConfiguration.class);
   assertThat(context.getBeansOfType(Filter.class).size()).isEqualTo(0);
   context.close();
 }
  @Test
  public void testEndpointMBeanExporterInParentChild()
      throws IntrospectionException, InstanceNotFoundException, MalformedObjectNameException,
          ReflectionException {
    this.context = new AnnotationConfigApplicationContext();
    this.context.register(
        JmxAutoConfiguration.class,
        EndpointAutoConfiguration.class,
        EndpointMBeanExportAutoConfiguration.class);

    AnnotationConfigApplicationContext parent = new AnnotationConfigApplicationContext();
    parent.register(
        JmxAutoConfiguration.class,
        EndpointAutoConfiguration.class,
        EndpointMBeanExportAutoConfiguration.class);
    this.context.setParent(parent);

    parent.refresh();
    this.context.refresh();

    parent.close();

    System.out.println("parent " + ObjectUtils.getIdentityHexString(parent));
    System.out.println("child " + ObjectUtils.getIdentityHexString(this.context));
  }
 @Test
 public void defaultManagementServerProperties() {
   AnnotationConfigApplicationContext context =
       new AnnotationConfigApplicationContext(ManagementServerPropertiesAutoConfiguration.class);
   assertThat(context.getBean(ManagementServerProperties.class).getPort(), nullValue());
   context.close();
 }
Пример #23
0
 @Ignore // TODO: SPR-6327
 @Test
 public void testImportDifferentResourceTypes() {
   AnnotationConfigApplicationContext ctx =
       new AnnotationConfigApplicationContext(SubResourceConfig.class);
   assertTrue(ctx.containsBean("propertiesDeclaredBean"));
   assertTrue(ctx.containsBean("xmlDeclaredBean"));
 }
Пример #24
0
 public static void main(String[] args) {
   LOGGER.info("Starting ...");
   AnnotationConfigApplicationContext ctx =
       new AnnotationConfigApplicationContext(AppConfig.class);
   DemoService service = (DemoService) ctx.getBean("DemoService");
   service.doSomethig();
   ctx.registerShutdownHook();
 }
Пример #25
0
 public static void main(String[] args) throws InterruptedException {
   AnnotationConfigApplicationContext context =
       new AnnotationConfigApplicationContext(Config.class);
   while (true) {
     context.getBean(ColorFrame.class).showOnRandomPlace();
     Thread.sleep(1000);
   }
 }
Пример #26
0
 public static void main(String[] args) {
   AnnotationConfigApplicationContext annotationConfigApplicationContext =
       new AnnotationConfigApplicationContext();
   annotationConfigApplicationContext.register(CustomizeScanTest.class);
   annotationConfigApplicationContext.refresh();
   ScanClass1 injectClass = annotationConfigApplicationContext.getBean(ScanClass1.class);
   injectClass.print();
 }
Пример #27
0
 public void testWithConfigurationClass() throws Exception {
   AnnotationConfigApplicationContext parent = new AnnotationConfigApplicationContext();
   parent.register(TransactionManagerConfiguration.class);
   parent.refresh();
   ClassPathXmlApplicationContext context =
       new ClassPathXmlApplicationContext(
           new String[] {"annotationDrivenConfigurationClassTests.xml"}, getClass(), parent);
   doTestWithMultipleTransactionManagers(context);
 }
 @Test
 public void strictTraceId_defaultsToTrue() {
   context = new AnnotationConfigApplicationContext();
   addEnvironment(context, "zipkin.storage.type:mysql");
   context.register(
       PropertyPlaceholderAutoConfiguration.class, ZipkinMySQLStorageAutoConfiguration.class);
   context.refresh();
   assertThat(context.getBean(MySQLStorage.class).strictTraceId).isTrue();
 }
 @Test
 public void spr11249() throws Exception {
   AnnotationConfigApplicationContext context =
       new AnnotationConfigApplicationContext(Spr11249Config.class);
   Spr11249Service bean = context.getBean(Spr11249Service.class);
   Object result = bean.doSomething("op", 2, 3);
   assertSame(result, bean.doSomething("op", 2, 3));
   context.close();
 }
 @Test
 public void definedManagementServerProperties() throws Exception {
   AnnotationConfigApplicationContext context =
       new AnnotationConfigApplicationContext(
           Config.class, ManagementServerPropertiesAutoConfiguration.class);
   assertThat(
       context.getBean(ManagementServerProperties.class).getPort(), equalTo(Integer.valueOf(123)));
   context.close();
 }