コード例 #1
0
  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();
    }
  }
 @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();
 }
コード例 #3
0
 @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();
   }
 }
コード例 #4
0
 @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 defaultManagementServerProperties() {
   AnnotationConfigApplicationContext context =
       new AnnotationConfigApplicationContext(ManagementServerPropertiesAutoConfiguration.class);
   assertThat(context.getBean(ManagementServerProperties.class).getPort(), nullValue());
   context.close();
 }
コード例 #6
0
ファイル: SpringJavaConfig.java プロジェクト: vamsigoli/basic
  public static void main(String[] args) {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    ctx.scan("com.vamsi");
    ctx.refresh();

    for (String beanname : ctx.getBeanDefinitionNames()) {

      System.out.println(beanname);
    }

    HollywoodServiceJSR330 hollywoodservice =
        ctx.getBean("hollywoodServiceJSR330", HollywoodServiceJSR330.class);

    hollywoodservice.getFriendlyAgents();

    Box<Integer> abox = ctx.getBean("intBox", Box.class);

    abox.setA(100);

    System.out.println("first bean " + abox.getA());

    Box<Integer> bbox = ctx.getBean("intBox", Box.class);

    System.out.println("second bean " + abox.getA());

    ctx.close();
  }
コード例 #7
0
  @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();
  }
  @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));
  }
コード例 #9
0
ファイル: SmartCSV.java プロジェクト: justfriend/SmartCSV.fx
  @Override
  public void stop() throws Exception {
    if (appContext != null) {
      appContext.close();
    }

    super.stop();
  }
コード例 #10
0
 @After
 public void clean() {
   machine.stop();
   context.close();
   context = null;
   machine = null;
   tasks = null;
   listener = null;
 }
コード例 #11
0
 @Test
 public void skipsFilterIfPropertyDisabled() throws Exception {
   AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
   EnvironmentTestUtils.addEnvironment(context, "endpoints.metrics.filter.enabled:false");
   context.register(Config.class, MetricFilterAutoConfiguration.class);
   context.refresh();
   assertThat(context.getBeansOfType(Filter.class).size()).isEqualTo(0);
   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();
 }
コード例 #13
0
 @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();
 }
コード例 #14
0
ファイル: ConfigReadTest.java プロジェクト: yongzhian/zain
  @Test
  public void configReadTest() throws Exception {
    AnnotationConfigApplicationContext context =
        new AnnotationConfigApplicationContext(ConfigRead.class);
    ConfigRead configRead = context.getBean(ConfigRead.class);
    logger.info(configRead);

    context.close(); // 销毁spring容器对象
  }
コード例 #15
0
 @Test
 public void spr11124() throws Exception {
   AnnotationConfigApplicationContext context =
       new AnnotationConfigApplicationContext(Spr11124Config.class);
   Spr11124Service bean = context.getBean(Spr11124Service.class);
   bean.single(2);
   bean.single(2);
   bean.multiple(2);
   bean.multiple(2);
   context.close();
 }
コード例 #16
0
 @Test
 public void testParentChildAnnotationConfigurationFromAnotherPackage() {
   AnnotationConfigApplicationContext child = new AnnotationConfigApplicationContext();
   child.register(org.springframework.integration.configuration2.ChildConfiguration.class);
   child.setParent(this.context);
   child.refresh();
   AbstractMessageChannel foo = child.getBean("foo", AbstractMessageChannel.class);
   ChannelInterceptor baz = child.getBean("baz", ChannelInterceptor.class);
   assertTrue(foo.getChannelInterceptors().contains(baz));
   assertFalse(this.output.getChannelInterceptors().contains(baz));
   child.close();
 }
コード例 #17
0
ファイル: Main.java プロジェクト: 354447958/test
  public static void main(String[] args) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Main.class);
    System.out.println("按任意键退出");

    try {
      System.in.read();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      context.close();
    }
  }
コード例 #18
0
  public static void main(final String[] args) {
    // Initialize spring context to create DB schema
    AnnotationConfigApplicationContext applicationContext = null;

    applicationContext = createApplicationContext();

    if (null != applicationContext) {
      applicationContext.close();
    }

    System.exit(0);
  }
コード例 #19
0
 public static void main(String[] args) throws IOException {
   try {
     AnnotationConfigApplicationContext cxt =
         new AnnotationConfigApplicationContext(ClientConfig.class);
     System.in.read();
     cxt.close();
   } catch (Throwable t) {
     t.printStackTrace();
   } finally {
     System.exit(0);
   }
 }
コード例 #20
0
 @Test
 public void recordsHttpInteractionsWithTemplateVariable() throws Exception {
   AnnotationConfigApplicationContext context =
       new AnnotationConfigApplicationContext(Config.class, MetricFilterAutoConfiguration.class);
   Filter filter = context.getBean(Filter.class);
   MockMvc mvc =
       MockMvcBuilders.standaloneSetup(new MetricFilterTestController()).addFilter(filter).build();
   mvc.perform(get("/templateVarTest/foo")).andExpect(status().isOk());
   verify(context.getBean(CounterService.class))
       .increment("status.200.templateVarTest.someVariable");
   verify(context.getBean(GaugeService.class))
       .submit(eq("response.templateVarTest.someVariable"), anyDouble());
   context.close();
 }
コード例 #21
0
 @Test
 public void records404HttpInteractionsAsSingleMetric() throws Exception {
   AnnotationConfigApplicationContext context =
       new AnnotationConfigApplicationContext(Config.class, MetricFilterAutoConfiguration.class);
   Filter filter = context.getBean(Filter.class);
   MockMvc mvc =
       MockMvcBuilders.standaloneSetup(new MetricFilterTestController()).addFilter(filter).build();
   mvc.perform(get("/unknownPath/1")).andExpect(status().isNotFound());
   mvc.perform(get("/unknownPath/2")).andExpect(status().isNotFound());
   verify(context.getBean(CounterService.class), times(2)).increment("status.404.unmapped");
   verify(context.getBean(GaugeService.class), times(2))
       .submit(eq("response.unmapped"), anyDouble());
   context.close();
 }
コード例 #22
0
 @Test
 public void renderNonWebAppTemplate() throws Exception {
   AnnotationConfigApplicationContext context =
       new AnnotationConfigApplicationContext(
           ThymeleafAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class);
   assertThat(context.getBeanNamesForType(ViewResolver.class).length).isEqualTo(0);
   try {
     TemplateEngine engine = context.getBean(TemplateEngine.class);
     Context attrs = new Context(Locale.UK, Collections.singletonMap("greeting", "Hello World"));
     String result = engine.process("message", attrs);
     assertThat(result).contains("Hello World");
   } finally {
     context.close();
   }
 }
コード例 #23
0
 @Test
 public void testFilterIsNotRegisteredInNonWeb() throws Exception {
   AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
   context.register(
       SecurityAutoConfiguration.class,
       SecurityFilterAutoConfiguration.class,
       ServerPropertiesAutoConfiguration.class,
       PropertyPlaceholderAutoConfiguration.class);
   try {
     context.refresh();
     assertFalse(context.containsBean("securityFilterChainRegistration"));
   } finally {
     context.close();
   }
 }
コード例 #24
0
 @Test
 public void controllerMethodThatThrowsUnhandledException() throws Exception {
   AnnotationConfigApplicationContext context =
       new AnnotationConfigApplicationContext(Config.class, MetricFilterAutoConfiguration.class);
   Filter filter = context.getBean(Filter.class);
   MockMvc mvc =
       MockMvcBuilders.standaloneSetup(new MetricFilterTestController()).addFilter(filter).build();
   try {
     mvc.perform(get("/unhandledException")).andExpect(status().isInternalServerError());
   } catch (NestedServletException ex) {
     // Expected
   }
   verify(context.getBean(CounterService.class)).increment("status.500.unhandledException");
   verify(context.getBean(GaugeService.class))
       .submit(eq("response.unhandledException"), anyDouble());
   context.close();
 }
コード例 #25
0
  @Test
  public void spr11592GetNeverCache() {
    AnnotationConfigApplicationContext context =
        new AnnotationConfigApplicationContext(Spr11592Config.class);
    Spr11592Service bean = context.getBean(Spr11592Service.class);
    Cache cache = context.getBean("cache", Cache.class);

    String key = "1";
    Object result = bean.getNeverCache("1");
    verify(cache, times(0)).get(key); // no cache hit at all, caching disabled

    Object cachedResult = bean.getNeverCache("1");
    assertNotSame(result, cachedResult);
    verify(cache, times(0)).get(key); // caching disabled

    context.close();
  }
コード例 #26
0
  @Test
  public void spr11592GetSimple() {
    AnnotationConfigApplicationContext context =
        new AnnotationConfigApplicationContext(Spr11592Config.class);
    Spr11592Service bean = context.getBean(Spr11592Service.class);
    Cache cache = context.getBean("cache", Cache.class);

    String key = "1";
    Object result = bean.getSimple("1");
    verify(cache, times(1)).get(key); // first call: cache miss

    Object cachedResult = bean.getSimple("1");
    assertSame(result, cachedResult);
    verify(cache, times(2)).get(key); // second call: cache hit

    context.close();
  }
コード例 #27
0
  public static void main(String[] args) {

    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    ctx.getEnvironment().setActiveProfiles("highschool");
    ctx.register(KindergartenConfig.class, HighschoolConfig.class);
    ctx.refresh();

    FoodProviderService foodProviderService =
        ctx.getBean("foodProviderService", FoodProviderService.class);
    List<Food> lunchSet = foodProviderService.provideLunchSet();

    for (Food food : lunchSet) {
      System.out.println("  Food: " + food.getName());
    }

    ctx.close();
  }
コード例 #28
0
  @Test
  public void customExecutorIsPropagated() throws InterruptedException {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    ctx.register(CustomExecutorAsyncConfig.class);
    ctx.refresh();

    AsyncBean asyncBean = ctx.getBean(AsyncBean.class);
    asyncBean.work();
    Thread.sleep(500);
    assertThat(asyncBean.getThreadOfExecution().getName(), startsWith("Custom-"));

    TestableAsyncUncaughtExceptionHandler exceptionHandler =
        (TestableAsyncUncaughtExceptionHandler) ctx.getBean("exceptionHandler");
    assertFalse("handler should not have been called yet", exceptionHandler.isCalled());

    asyncBean.fail();
    Thread.sleep(500);
    Method m = ReflectionUtils.findMethod(AsyncBean.class, "fail");
    exceptionHandler.assertCalledWith(m, UnsupportedOperationException.class);

    ctx.close();
  }
コード例 #29
0
 @Test
 public void recordsHttpInteractions() throws Exception {
   AnnotationConfigApplicationContext context =
       new AnnotationConfigApplicationContext(Config.class, MetricFilterAutoConfiguration.class);
   Filter filter = context.getBean(Filter.class);
   final MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test/path");
   final MockHttpServletResponse response = new MockHttpServletResponse();
   FilterChain chain = mock(FilterChain.class);
   willAnswer(
           new Answer<Object>() {
             @Override
             public Object answer(InvocationOnMock invocation) throws Throwable {
               response.setStatus(200);
               return null;
             }
           })
       .given(chain)
       .doFilter(request, response);
   filter.doFilter(request, response, chain);
   verify(context.getBean(CounterService.class)).increment("status.200.test.path");
   verify(context.getBean(GaugeService.class)).submit(eq("response.test.path"), anyDouble());
   context.close();
 }
コード例 #30
0
 @After
 public void close() {
   if (context != null) {
     context.close();
   }
 }