org.springframework.context.ApplicationListener类的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(17.2k)|赞(0)|评价(0)|浏览(184)

本文整理了Java中org.springframework.context.ApplicationListener类的一些代码示例,展示了ApplicationListener类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ApplicationListener类的具体详情如下:
包路径:org.springframework.context.ApplicationListener
类名称:ApplicationListener

ApplicationListener介绍

[英]Interface to be implemented by application event listeners. Based on the standard java.util.EventListener interface for the Observer design pattern.

As of Spring 3.0, an ApplicationListener can generically declare the event type that it is interested in. When registered with a Spring ApplicationContext, events will be filtered accordingly, with the listener getting invoked for matching event objects only.
[中]由应用程序事件侦听器实现的接口。基于标准java。util。观察者设计模式的EventListener接口。
从Spring3.0开始,ApplicationListener可以一般性地声明它感兴趣的事件类型。当使用SpringApplicationContext注册时,事件将被相应地过滤,侦听器仅被调用用于匹配事件对象。

代码示例

代码示例来源:origin: spring-projects/spring-framework

@Override
public void onApplicationEvent(ApplicationEvent event) {
  this.delegate.onApplicationEvent(event);
}

代码示例来源:origin: org.springframework/spring-context

@Override
public void onApplicationEvent(ApplicationEvent event) {
  this.delegate.onApplicationEvent(event);
}

代码示例来源:origin: spring-projects/spring-data-mongodb

@SuppressWarnings("unchecked")
public void publishEvent(ApplicationEvent event) {
  if (event instanceof MappingContextEvent) {
    indexCreator.onApplicationEvent((MappingContextEvent<MongoPersistentEntity<?>, MongoPersistentProperty>) event);
  }
}

代码示例来源:origin: spring-projects/spring-framework

@SuppressWarnings({"unchecked", "rawtypes"})
private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {
  try {
    listener.onApplicationEvent(event);
  }
  catch (ClassCastException ex) {
    String msg = ex.getMessage();
    if (msg == null || matchesClassCastMessage(msg, event.getClass())) {
      // Possibly a lambda-defined listener which we could not resolve the generic event type for
      // -> let's suppress the exception and just log a debug message.
      Log logger = LogFactory.getLog(getClass());
      if (logger.isDebugEnabled()) {
        logger.debug("Non-matching event type for listener: " + listener, ex);
      }
    }
    else {
      throw ex;
    }
  }
}

代码示例来源:origin: org.springframework/spring-context

@SuppressWarnings({"unchecked", "rawtypes"})
private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {
  try {
    listener.onApplicationEvent(event);
  }
  catch (ClassCastException ex) {
    String msg = ex.getMessage();
    if (msg == null || matchesClassCastMessage(msg, event.getClass())) {
      // Possibly a lambda-defined listener which we could not resolve the generic event type for
      // -> let's suppress the exception and just log a debug message.
      Log logger = LogFactory.getLog(getClass());
      if (logger.isDebugEnabled()) {
        logger.debug("Non-matching event type for listener: " + listener, ex);
      }
    }
    else {
      throw ex;
    }
  }
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void simpleApplicationEventMulticasterWithErrorHandler() {
  @SuppressWarnings("unchecked")
  ApplicationListener<ApplicationEvent> listener = mock(ApplicationListener.class);
  ApplicationEvent evt = new ContextClosedEvent(new StaticApplicationContext());
  SimpleApplicationEventMulticaster smc = new SimpleApplicationEventMulticaster();
  smc.setErrorHandler(TaskUtils.LOG_AND_SUPPRESS_ERROR_HANDLER);
  smc.addApplicationListener(listener);
  willThrow(new RuntimeException()).given(listener).onApplicationEvent(evt);
  smc.multicastEvent(evt);
}

代码示例来源:origin: spring-projects/spring-framework

private void multicastEvent(boolean match, Class<?> listenerType, ApplicationEvent event, ResolvableType eventType) {
  @SuppressWarnings("unchecked")
  ApplicationListener<ApplicationEvent> listener =
      (ApplicationListener<ApplicationEvent>) mock(listenerType);
  SimpleApplicationEventMulticaster smc = new SimpleApplicationEventMulticaster();
  smc.addApplicationListener(listener);
  if (eventType != null) {
    smc.multicastEvent(event, eventType);
  }
  else {
    smc.multicastEvent(event);
  }
  int invocation = match ? 1 : 0;
  verify(listener, times(invocation)).onApplicationEvent(event);
}

代码示例来源:origin: org.springframework.data/spring-data-mongodb

@SuppressWarnings("unchecked")
public void publishEvent(ApplicationEvent event) {
  if (event instanceof MappingContextEvent) {
    indexCreator.onApplicationEvent((MappingContextEvent<MongoPersistentEntity<?>, MongoPersistentProperty>) event);
  }
}

代码示例来源:origin: cloudfoundry/uaa

@Test
void clientAuthenticationSuccess() throws Exception {
  ArgumentCaptor<AbstractUaaEvent> captor = ArgumentCaptor.forClass(AbstractUaaEvent.class);
  String basicDigestHeaderValue = "Basic "
      + new String(Base64.encodeBase64(("login:loginsecret").getBytes()));
  MockHttpServletRequestBuilder oauthTokenPost = post("/oauth/token")
      .header("Authorization", basicDigestHeaderValue)
      .param("grant_type", "client_credentials")
      .param("scope", "oauth.login");
  mockMvc.perform(oauthTokenPost).andExpect(status().isOk());
  verify(listener, times(2)).onApplicationEvent(captor.capture());
  ClientAuthenticationSuccessEvent event = (ClientAuthenticationSuccessEvent) captor.getAllValues().get(0);
  assertEquals("login", event.getClientId());
  AuditEvent auditEvent = event.getAuditEvent();
  assertEquals("login", auditEvent.getPrincipalId());
}

代码示例来源:origin: cloudfoundry/uaa

@Test
void clientAuthenticationFailureClientNotFound() throws Exception {
  ArgumentCaptor<AbstractUaaEvent> captor = ArgumentCaptor.forClass(AbstractUaaEvent.class);
  String basicDigestHeaderValue = "Basic "
      + new String(Base64.encodeBase64(("login2:loginsecret").getBytes()));
  MockHttpServletRequestBuilder oauthTokenPost = post("/oauth/token")
      .header("Authorization", basicDigestHeaderValue)
      .param("grant_type", "client_credentials")
      .param("client_id", "login")
      .param("scope", "oauth.login");
  mockMvc.perform(oauthTokenPost).andExpect(status().isUnauthorized());
  verify(listener, atLeast(1)).onApplicationEvent(captor.capture());
  PrincipalAuthenticationFailureEvent event0 = (PrincipalAuthenticationFailureEvent) captor.getAllValues().get(0);
  assertEquals("login2", event0.getAuditEvent().getPrincipalId());
  ClientAuthenticationFailureEvent event1 = (ClientAuthenticationFailureEvent) captor.getAllValues().get(1);
  assertEquals("login", event1.getClientId());
}

代码示例来源:origin: cloudfoundry/uaa

@Test
void clientAuthenticationFailure() throws Exception {
  ArgumentCaptor<AbstractUaaEvent> captor = ArgumentCaptor.forClass(AbstractUaaEvent.class);
  String basicDigestHeaderValue = "Basic "
      + new String(Base64.encodeBase64(("login:loginsecretwrong").getBytes()));
  MockHttpServletRequestBuilder oauthTokenPost = post("/oauth/token")
      .header("Authorization", basicDigestHeaderValue)
      .param("grant_type", "client_credentials")
      .param("scope", "oauth.login");
  mockMvc.perform(oauthTokenPost).andExpect(status().isUnauthorized());
  verify(listener, times(2)).onApplicationEvent(captor.capture());
  ClientAuthenticationFailureEvent event = (ClientAuthenticationFailureEvent) captor.getValue();
  assertEquals("login", event.getClientId());
  AuditEvent auditEvent = event.getAuditEvent();
  assertEquals("login", auditEvent.getPrincipalId());
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void simpleApplicationEventMulticasterWithException() {
  @SuppressWarnings("unchecked")
  ApplicationListener<ApplicationEvent> listener = mock(ApplicationListener.class);
  ApplicationEvent evt = new ContextClosedEvent(new StaticApplicationContext());
  SimpleApplicationEventMulticaster smc = new SimpleApplicationEventMulticaster();
  smc.addApplicationListener(listener);
  RuntimeException thrown = new RuntimeException();
  willThrow(thrown).given(listener).onApplicationEvent(evt);
  try {
    smc.multicastEvent(evt);
    fail("Should have thrown RuntimeException");
  }
  catch (RuntimeException ex) {
    assertSame(thrown, ex);
  }
}

代码示例来源:origin: cloudfoundry/uaa

@Test
public void testAuthenticateFailure() throws Exception {
  String username = "marissa3";
  String password = "ldapsadadasas";
  MockHttpServletRequestBuilder post =
    post("/authenticate")
      .header(HOST, host)
      .accept(MediaType.APPLICATION_JSON)
      .param("username", username)
      .param("password", password);
  getMockMvc().perform(post)
    .andExpect(status().isUnauthorized());
  ArgumentCaptor<AbstractUaaEvent> captor = ArgumentCaptor.forClass(AbstractUaaEvent.class);
  verify(listener, atLeast(5)).onApplicationEvent(captor.capture());
  List<AbstractUaaEvent> allValues = captor.getAllValues();
  assertThat(allValues.get(3), instanceOf(IdentityProviderAuthenticationFailureEvent.class));
  IdentityProviderAuthenticationFailureEvent event = (IdentityProviderAuthenticationFailureEvent)allValues.get(3);
  assertEquals("marissa3", event.getUsername());
  assertEquals(OriginKeys.LDAP, event.getAuthenticationType());
}

代码示例来源:origin: cloudfoundry/uaa

@Test
public void testGoogleAuthenticatorLoginFlow() throws Exception {
  redirectToMFARegistration();
  performGetMfaRegister()
   .andDo(print())
   .andExpect(view().name("mfa/qr_code"));
  assertFalse(userGoogleMfaCredentialsProvisioning.activeUserCredentialExists(user.getId(), mfaProvider.getId()));
  int code = MockMvcUtils.getMFACodeFromSession(session);
  String location = MockMvcUtils.performMfaPostVerifyWithCode(code, getMockMvc(), session);
  ArgumentCaptor<AbstractUaaEvent> eventCaptor = ArgumentCaptor.forClass(AbstractUaaEvent.class);
  verify(listener, atLeast(1)).onApplicationEvent(eventCaptor.capture());
  assertEquals(8, eventCaptor.getAllValues().size());
  assertThat(eventCaptor.getAllValues().get(6), instanceOf(MfaAuthenticationSuccessEvent.class));
  getMockMvc().perform(get(location)
   .session(session))
   .andExpect(status().isFound())
   .andExpect(redirectedUrl("http://localhost/"));
  session = new MockHttpSession();
  performLoginWithSession();
  MockMvcUtils.performMfaPostVerifyWithCode(code, getMockMvc(), session);
  eventCaptor = ArgumentCaptor.forClass(AbstractUaaEvent.class);
  verify(listener, atLeast(1)).onApplicationEvent(eventCaptor.capture());
  assertEquals(14, eventCaptor.getAllValues().size());
  assertThat(eventCaptor.getAllValues().get(12), instanceOf(MfaAuthenticationSuccessEvent.class));
}

代码示例来源:origin: cloudfoundry/uaa

@Test
void password_change_recorded_at_dao(@Autowired ScimUserProvisioning provisioning) {
  ScimUser user = new ScimUser(null, new RandomValueStringGenerator().generate() + "@test.org", "first", "last");
  user.setPrimaryEmail(user.getUserName());
  user = provisioning.createUser(user, "oldpassword", IdentityZoneHolder.get().getId());
  provisioning.changePassword(user.getId(), "oldpassword", "newpassword", IdentityZoneHolder.get().getId());
  ArgumentCaptor<AbstractUaaEvent> captor = ArgumentCaptor.forClass(AbstractUaaEvent.class);
  verify(listener, times(2)).onApplicationEvent(captor.capture());
  //the last event should be our password modified event
  PasswordChangeEvent pw = (PasswordChangeEvent) captor.getValue();
  assertEquals(user.getUserName(), pw.getUser().getUsername());
  assertEquals("Password changed", pw.getMessage());
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void simpleApplicationEventMulticasterWithTaskExecutor() {
  @SuppressWarnings("unchecked")
  ApplicationListener<ApplicationEvent> listener = mock(ApplicationListener.class);
  ApplicationEvent evt = new ContextClosedEvent(new StaticApplicationContext());
  SimpleApplicationEventMulticaster smc = new SimpleApplicationEventMulticaster();
  smc.setTaskExecutor(new Executor() {
    @Override
    public void execute(Runnable command) {
      command.run();
      command.run();
    }
  });
  smc.addApplicationListener(listener);
  smc.multicastEvent(evt);
  verify(listener, times(2)).onApplicationEvent(evt);
}

代码示例来源:origin: cloudfoundry/uaa

@Test
public void testManualRegistrationFlow() throws Exception {
  redirectToMFARegistration();
  assertFalse(userGoogleMfaCredentialsProvisioning.activeUserCredentialExists(user.getId(), mfaProvider.getId()));
  performGetMfaManualRegister().andExpect((view().name("mfa/manual_registration")));
  int code = MockMvcUtils.getMFACodeFromSession(session);
  String location = MockMvcUtils.performMfaPostVerifyWithCode(code, getMockMvc(), session);
  assertEquals("/login/mfa/completed", location);
  ArgumentCaptor<AbstractUaaEvent> eventCaptor = ArgumentCaptor.forClass(AbstractUaaEvent.class);
  verify(listener, atLeast(1)).onApplicationEvent(eventCaptor.capture());
  assertEquals(8, eventCaptor.getAllValues().size());
  assertThat(eventCaptor.getAllValues().get(6), instanceOf(MfaAuthenticationSuccessEvent.class));
  getMockMvc().perform(get("/")
   .session(session))
   .andExpect(status().isOk())
   .andExpect(view().name("home"));
  getMockMvc().perform(get("/logout.do")).andReturn();
  session = new MockHttpSession();
  performLoginWithSession();
  MockMvcUtils.performMfaPostVerifyWithCode(code, getMockMvc(), session);
  eventCaptor = ArgumentCaptor.forClass(AbstractUaaEvent.class);
  verify(listener, atLeast(1)).onApplicationEvent(eventCaptor.capture());
  assertEquals(15, eventCaptor.getAllValues().size());
  assertThat(eventCaptor.getAllValues().get(13), instanceOf(MfaAuthenticationSuccessEvent.class));
}

代码示例来源:origin: cloudfoundry/uaa

@Test
void userNotFoundLoginUnsuccessfulTest() throws Exception {
  String username = "test1234";
  MockHttpSession session = new MockHttpSession();
  MockHttpServletRequestBuilder loginPost = post("/login.do")
      .with(cookieCsrf())
      .session(session)
      .accept(MediaType.TEXT_HTML_VALUE)
      .param("username", username)
      .param("password", testPassword);
  //success means a 302 to / (failure is 302 to /login?error...)
  mockMvc.perform(loginPost)
      .andExpect(status().is3xxRedirection())
      .andExpect(header().string("Location", "/login?error=login_failure"));
  ArgumentCaptor<AbstractUaaEvent> captor = ArgumentCaptor.forClass(AbstractUaaEvent.class);
  verify(listener, atLeast(2)).onApplicationEvent(captor.capture());
  UserNotFoundEvent event1 = (UserNotFoundEvent) captor.getAllValues().get(0);
  assertTrue(event1.getAuditEvent().getOrigin().contains("sessionId=<SESSION>"));
  PrincipalAuthenticationFailureEvent event2 = (PrincipalAuthenticationFailureEvent) captor.getAllValues().get(1);
  assertEquals(username, ((Authentication) event1.getSource()).getName());
  assertEquals(username, event2.getName());
  assertFalse(event2.getAuditEvent().getOrigin().contains("sessionId=<SESSION>")); //PrincipalAuthenticationFailureEvent does not contain sessionId at all
}

代码示例来源:origin: cloudfoundry/uaa

@Test
void unverifiedLegacyUserAuthenticationWhenAllowedTest(
    @Autowired List<JdbcTemplate> jdbcTemplates
) throws Exception {
  mgr.setAllowUnverifiedUsers(true);
  String adminToken = testClient.getClientCredentialsOAuthAccessToken(
      testAccounts.getAdminClientId(),
      testAccounts.getAdminClientSecret(),
      "uaa.admin,scim.write");
  ScimUser molly = createUser(adminToken, "molly", "Molly", "Collywobble", "molly@example.com", "wobblE3", false);
  jdbcTemplates.forEach(jdbc -> jdbc.execute("update users set legacy_verification_behavior = " + dbTrueString + " where origin='uaa' and username = '" + molly.getUserName() + "'"));
  MockHttpSession session = new MockHttpSession();
  MockHttpServletRequestBuilder loginPost = post("/authenticate")
      .accept(APPLICATION_JSON_VALUE)
      .session(session)
      .param("username", molly.getUserName())
      .param("password", "wobblE3");
  mockMvc.perform(loginPost)
      .andExpect(status().isOk());
  ArgumentCaptor<UserAuthenticationSuccessEvent> captor = ArgumentCaptor.forClass(UserAuthenticationSuccessEvent.class);
  verify(authSuccessListener, times(1)).onApplicationEvent(captor.capture());
  UserAuthenticationSuccessEvent event = captor.getValue();
  assertEquals(molly.getUserName(), event.getUser().getUsername());
  assertTrue(event.getAuditEvent().getOrigin().contains("sessionId=<SESSION>"));
}

代码示例来源:origin: cloudfoundry/uaa

@Test
void invalidPasswordLoginAuthenticateEndpointTest() throws Exception {
  MockHttpSession session = new MockHttpSession();
  MockHttpServletRequestBuilder loginPost = post("/authenticate")
      .accept(APPLICATION_JSON_VALUE)
      .session(session)
      .param("username", testUser.getUserName())
      .param("password", "");
  mockMvc.perform(loginPost)
      .andExpect(status().isUnauthorized())
      .andExpect(content().string("{\"error\":\"authentication failed\"}"));
  ArgumentCaptor<AbstractUaaEvent> captor = ArgumentCaptor.forClass(AbstractUaaEvent.class);
  verify(listener, atLeast(3)).onApplicationEvent(captor.capture());
  IdentityProviderAuthenticationFailureEvent event1 = (IdentityProviderAuthenticationFailureEvent) captor.getAllValues().get(0);
  UserAuthenticationFailureEvent event2 = (UserAuthenticationFailureEvent) captor.getAllValues().get(1);
  PrincipalAuthenticationFailureEvent event3 = (PrincipalAuthenticationFailureEvent) captor.getAllValues().get(2);
  assertEquals(testUser.getUserName(), event1.getUsername());
  assertEquals(testUser.getUserName(), event2.getUser().getUsername());
  assertEquals(testUser.getUserName(), event3.getName());
  assertTrue(event1.getAuditEvent().getOrigin().contains("sessionId=<SESSION>"));
  assertTrue(event2.getAuditEvent().getOrigin().contains("sessionId=<SESSION>"));
  assertFalse(event3.getAuditEvent().getOrigin().contains("sessionId=<SESSION>")); //PrincipalAuthenticationFailureEvent does not contain sessionId at all
}

相关文章

微信公众号

最新文章

更多

ApplicationListener类方法