Example usage for org.springframework.context ApplicationEventPublisher ApplicationEventPublisher

List of usage examples for org.springframework.context ApplicationEventPublisher ApplicationEventPublisher

Introduction

In this page you can find the example usage for org.springframework.context ApplicationEventPublisher ApplicationEventPublisher.

Prototype

ApplicationEventPublisher

Source Link

Usage

From source file:de.hska.ld.core.config.security.openidconnect.OIDCSecurityConfig.java

@Override
@SuppressWarnings("unchecked")
protected void configure(HttpSecurity http) throws Exception {
    OIDCAuthenticationFilter oidcFilter = openIdConnectAuthenticationFilter();
    oidcFilter.setAuthenticationSuccessHandler(new AuthenticationSuccessHandler() {
        @Override/*  www . j av a2 s.  c o  m*/
        public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                Authentication authentication) throws IOException, ServletException {
            response.sendRedirect(env.getProperty("module.core.oidc.redirect.to.client"));
        }
    });
    oidcFilter.setApplicationEventPublisher(new ApplicationEventPublisher() {
        @Override
        public void publishEvent(ApplicationEvent event) {
            Object source = event.getSource();
            OIDCAuthenticationToken token = null;
            if (source != null) {
                token = (OIDCAuthenticationToken) source;
            }
            if (token != null) {
                Map map = (Map) token.getPrincipal();
                Iterator iterator = map.entrySet().iterator();
                String subId = null;
                String issuer = null;
                if (iterator.hasNext()) {
                    Map.Entry<String, String> entry = (Map.Entry<String, String>) iterator.next();
                    if ("sub".equals(entry.getKey())) {
                        // check if sub id is already present in the database
                        subId = entry.getValue();
                        if (subId == null) {
                            throw new UnsupportedOperationException("No subId found!");
                        }
                    }
                }
                if (iterator.hasNext()) {
                    Map.Entry<String, String> entry = (Map.Entry<String, String>) iterator.next();
                    if ("iss".equals(entry.getKey())) {
                        issuer = entry.getValue();
                        if (!env.getProperty("module.core.oidc.identity.provider.url").equals(issuer)) {
                            throw new UnsupportedOperationException("Wrong or no issuer found!");
                        }
                    }
                }

                User currentUserInDb = userService.findBySubIdAndIssuer(subId, issuer);
                UserInfo oidcUserInfo = ((OIDCAuthenticationToken) source).getUserInfo();

                if (currentUserInDb == null && oidcUserInfo != null) {
                    User savedUser = createNewUserFirstLogin(token, subId, issuer, oidcUserInfo);
                    try {
                        userEventsPublisher.sendUserLoginEvent(savedUser);
                        userEventsPublisher.sendUserFirstLoginEvent(savedUser);
                    } catch (Exception e) {
                        //
                    }
                    LoggingContext.put("user_email", EscapeUtil.escapeJsonForLogging(savedUser.getEmail()));
                    Logger.trace("User logs in for the first time.");
                    LoggingContext.clear();
                } else if (oidcUserInfo != null) {
                    User savedUser = updateUserInformationFromOIDC(token, currentUserInDb, oidcUserInfo);
                    try {
                        userEventsPublisher.sendUserLoginEvent(savedUser);
                    } catch (Exception e) {
                        //
                    }
                    LoggingContext.put("user_email", EscapeUtil.escapeJsonForLogging(savedUser.getEmail()));
                    Logger.trace("User logs in.");
                    LoggingContext.clear();
                } else {
                    // oidc information is null
                    throw new UnsupportedOperationException("No OIDC information found!");
                }
            }
        }

        private User updateUserInformationFromOIDC(OIDCAuthenticationToken token, User currentUserInDb,
                UserInfo oidcUserInfo) {
            // get the current authentication details of the user
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            enrichAuthoritiesWithStoredAuthorities(currentUserInDb, auth);

            // check for profile updates since the last login
            String oidcUpdatedTime = token.getUserInfo().getUpdatedTime();
            // oidc time: "20150701_090039"
            // oidc format: "yyyyMMdd_HHmmss"
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
            User savedUser = null;
            try {
                Date date = sdf.parse(oidcUpdatedTime);
                if (currentUserInDb.getEmail() == null
                        || currentUserInDb.getLastupdatedAt().getTime() > date.getTime()) {
                    currentUserInDb.setFullName(oidcUserInfo.getName());
                    currentUserInDb.setEmail(oidcUserInfo.getEmail());
                    savedUser = userService.save(currentUserInDb);
                } else {
                    savedUser = currentUserInDb;
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return savedUser;
        }

        private User createNewUserFirstLogin(OIDCAuthenticationToken token, String subId, String issuer,
                UserInfo oidcUserInfo) {
            // create a new user
            User user = new User();
            // check for colliding user names (via preferred user name)
            String prefferedUsername = oidcUserInfo.getPreferredUsername();
            User userWithGivenPreferredUserName = userService.findByUsername(prefferedUsername);
            int i = 0;
            if (userWithGivenPreferredUserName != null) {
                while (userWithGivenPreferredUserName != null) {
                    prefferedUsername = oidcUserInfo.getPreferredUsername() + "#" + i;
                    userWithGivenPreferredUserName = userService.findByUsername(prefferedUsername);
                }
            }
            user.setUsername(prefferedUsername);

            user.setFullName(oidcUserInfo.getName());
            user.setEmail(oidcUserInfo.getEmail());
            user.setEnabled(true);
            // apply roles
            List<Role> roleList = new ArrayList<Role>();
            Role userRole = roleService.findByName("ROLE_USER");
            if (userRole == null) {
                // create initial roles
                String newUserRoleName = "ROLE_USER";
                userRole = createNewUserRole(newUserRoleName);
                String newAdminRoleName = "ROLE_ADMIN";
                Role adminRole = createNewUserRole(newAdminRoleName);
                // For the first user add the admin role
                roleList.add(adminRole);
            } else {
                roleList.add(userRole);
            }
            user.setRoleList(roleList);
            // A password is required so we set a uuid generated one
            if ("development".equals(env.getProperty("lds.app.instance"))) {
                user.setPassword("pass");
            } else {
                user.setPassword(UUID.randomUUID().toString());
            }
            user.setSubId(subId);
            user.setIssuer(issuer);
            String oidcUpdatedTime = token.getUserInfo().getUpdatedTime();
            // oidc time: "20150701_090039"
            // oidc format: "yyyyMMdd_HHmmss"
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
            try {
                Date date = sdf.parse(oidcUpdatedTime);
                user.setLastupdatedAt(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }

            User savedUser = userService.save(user);

            // update security context
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            enrichAuthoritiesWithStoredAuthorities(user, auth);

            return savedUser;
        }

        @Override
        public void publishEvent(Object event) {
            throw new RuntimeException("Publish event call failed not implemented yet.");
        }

        private void enrichAuthoritiesWithStoredAuthorities(User currentUserInDb, Authentication auth) {
            Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
            final SubjectIssuerGrantedAuthority[] oidcAuthority = new SubjectIssuerGrantedAuthority[1];
            authorities.forEach(authority -> {
                if (authority instanceof SubjectIssuerGrantedAuthority) {
                    // extract the oidc authority information
                    oidcAuthority[0] = (SubjectIssuerGrantedAuthority) authority;
                }
            });

            // create new authorities that includes the authorities stored in the database
            // as well as the oidc authority
            ArrayList<GrantedAuthority> newAuthorities = new ArrayList<GrantedAuthority>();
            newAuthorities.add(oidcAuthority[0]);
            currentUserInDb.getRoleList().forEach(role -> {
                newAuthorities.add(new SimpleGrantedAuthority(role.getName()));
            });
            try {
                Field authoritiesField = AbstractAuthenticationToken.class.getDeclaredField("authorities");
                authoritiesField.setAccessible(true);
                authoritiesField.set(auth, newAuthorities);
            } catch (NoSuchFieldException | IllegalAccessException e) {
                e.printStackTrace();
            }
            // update the authority information in the security context
            SecurityContextHolder.getContext().setAuthentication(auth);
        }

        private Role createNewUserRole(String newRoleName) {
            Role newUserRole = new Role();
            newUserRole.setName(newRoleName);
            return roleService.save(newUserRole);
        }
    });

    http.addFilterBefore(oidcFilter, AbstractPreAuthenticatedProcessingFilter.class).csrf()
            .requireCsrfProtectionMatcher(new RequestMatcher() {
                private Pattern allowedMethods = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");

                private RegexRequestMatcher apiMatcher = new RegexRequestMatcher("/v[0-9]*/.*", null);

                @Override
                public boolean matches(HttpServletRequest request) {
                    // CSRF disabled on allowedMethod
                    if (allowedMethods.matcher(request.getMethod()).matches())
                        return false;

                    // CSRF disabled on api calls
                    if (apiMatcher.matches(request))
                        return false;

                    // CSRF enables for other requests
                    //TODO change later on
                    return false;
                }
            }).and().exceptionHandling().authenticationEntryPoint(authenticationEntryPoint()).and().logout()
            .logoutSuccessHandler(logoutSuccessHandler()).deleteCookies("JSESSIONID")
            .deleteCookies("sessionID");
}

From source file:org.datacleaner.monitor.server.controllers.JobCopyAndDeleteControllerTest.java

public void testRenameJobAndResult() throws Exception {
    assertNull(repository.getRepositoryNode("/tenant1/jobs/product_analysis.analysis.xml"));

    final AtomicBoolean copyEventReceived = new AtomicBoolean(false);

    final JobCopyController jobCopyController = new JobCopyController();
    jobCopyController._contextFactory = tenantContextFactory;
    jobCopyController._eventPublisher = new ApplicationEventPublisher() {
        @Override//  w  ww. ja  va2s  .co  m
        public void publishEvent(ApplicationEvent event) {
            copyEventReceived.set(true);

            assertTrue(event instanceof JobCopyEvent);
            JobCopyEvent copyEvent = (JobCopyEvent) event;

            assertEquals("product_profiling", copyEvent.getSourceJob().getName());
            assertEquals("product_analysis", copyEvent.getTargetJob().getName());
        }
    };

    final JobCopyPayload input = new JobCopyPayload();
    input.setName("product_analysis");

    Map<String, String> result = jobCopyController.copyJob("tenant1", "product_profiling", input);
    assertEquals("{repository_url=/tenant1/jobs/product_analysis.analysis.xml, "
            + "source_job=product_profiling, target_job=product_analysis}", result.toString());

    assertNotNull(repository.getRepositoryNode("/tenant1/jobs/product_analysis.analysis.xml"));

    assertTrue(copyEventReceived.get());

    final AtomicBoolean deleteEventReceived = new AtomicBoolean(false);
    final JobDeletionController jobDeleteController = new JobDeletionController();
    jobDeleteController._contextFactory = tenantContextFactory;
    jobDeleteController._eventPublisher = new ApplicationEventPublisher() {
        @Override
        public void publishEvent(ApplicationEvent event) {
            deleteEventReceived.set(true);

            assertTrue(event instanceof JobDeletionEvent);
            JobDeletionEvent copyEvent = (JobDeletionEvent) event;

            assertEquals("product_analysis", copyEvent.getJobName());
        }
    };

    result = jobDeleteController.deleteJob("tenant1", "product_analysis");
    assertEquals("{action=delete, job=product_analysis}", result.toString());

    assertTrue(deleteEventReceived.get());

    assertNull(repository.getRepositoryNode("/tenant1/jobs/product_analysis.analysis.xml"));
}

From source file:org.datacleaner.monitor.server.controllers.JobModificationControllerTest.java

protected void setUp() throws Exception {
    File targetDir = new File("target/repo_job_modification");
    FileUtils.deleteDirectory(targetDir);
    FileUtils.copyDirectory(new File("src/test/resources/example_repo"), targetDir);
    repository = new FileRepository(targetDir);

    final TenantContextFactoryImpl tenantContextFactory = new TenantContextFactoryImpl(repository,
            new DataCleanerEnvironmentImpl(), new MockJobEngineManager());

    final ResultDao resultDao = new ResultDaoImpl(tenantContextFactory, null);
    timelineDao = new TimelineDaoImpl(tenantContextFactory, repository);

    jobModificationController = new JobModificationController();
    jobModificationListener1 = new JobModificationEventRenameResultsListener(resultDao);
    jobModificationListener2 = new JobModificationEventUpdateTimelinesListener(timelineDao);
    jobModificationController._contextFactory = tenantContextFactory;
    jobModificationController._eventPublisher = new ApplicationEventPublisher() {
        @Override//ww w .ja  v  a 2s  .c  o m
        public void publishEvent(ApplicationEvent event) {
            jobModificationListener1.onApplicationEvent((JobModificationEvent) event);
            jobModificationListener2.onApplicationEvent((JobModificationEvent) event);
        }
    };
}

From source file:org.datacleaner.monitor.server.controllers.ResultModificationControllerTest.java

protected void setUp() throws Exception {
    File targetDir = new File("target/repo_result_modification");
    FileUtils.deleteDirectory(targetDir);
    FileUtils.copyDirectory(new File("src/test/resources/example_repo"), targetDir);
    repository = new FileRepository(targetDir);

    TenantContextFactoryImpl tenantContextFactory = new TenantContextFactoryImpl(repository,
            new DataCleanerEnvironmentImpl(), new MockJobEngineManager());

    resultModificationController = new ResultModificationController();
    resultModificationListener = new ResultModificationEventExecutionLogListener(tenantContextFactory);

    final ApplicationEventPublisher applicationEventPublisher = new ApplicationEventPublisher() {
        @Override// w w w  .j a  va2 s.com
        public void publishEvent(ApplicationEvent event) {
            resultModificationListener.onApplicationEvent((ResultModificationEvent) event);
        }
    };

    resultModificationController._contextFactory = tenantContextFactory;
    resultModificationController._resultDao = new ResultDaoImpl(tenantContextFactory,
            applicationEventPublisher);
}

From source file:org.eobjects.datacleaner.monitor.server.controllers.JobModificationControllerTest.java

protected void setUp() throws Exception {
    File targetDir = new File("target/repo_job_modification");
    FileUtils.deleteDirectory(targetDir);
    FileUtils.copyDirectory(new File("src/test/resources/example_repo"), targetDir);
    repository = new FileRepository(targetDir);

    final TenantContextFactoryImpl tenantContextFactory = new TenantContextFactoryImpl(repository,
            new InjectionManagerFactoryImpl(), new MockJobEngineManager());

    final ResultDao resultDao = new ResultDaoImpl(tenantContextFactory, null);
    timelineDao = new TimelineDaoImpl(tenantContextFactory, repository);

    jobModificationController = new JobModificationController();
    jobModificationListener1 = new JobModificationEventRenameResultsListener(resultDao);
    jobModificationListener2 = new JobModificationEventUpdateTimelinesListener(timelineDao);
    jobModificationController._contextFactory = tenantContextFactory;
    jobModificationController._eventPublisher = new ApplicationEventPublisher() {
        @Override/* w  w w  .j a  va  2 s  .  c o  m*/
        public void publishEvent(ApplicationEvent event) {
            jobModificationListener1.onApplicationEvent((JobModificationEvent) event);
            jobModificationListener2.onApplicationEvent((JobModificationEvent) event);
        }
    };
}

From source file:org.eobjects.datacleaner.monitor.server.controllers.ResultModificationControllerTest.java

protected void setUp() throws Exception {
    File targetDir = new File("target/repo_result_modification");
    FileUtils.deleteDirectory(targetDir);
    FileUtils.copyDirectory(new File("src/test/resources/example_repo"), targetDir);
    repository = new FileRepository(targetDir);

    TenantContextFactoryImpl tenantContextFactory = new TenantContextFactoryImpl(repository,
            new InjectionManagerFactoryImpl(), new MockJobEngineManager());

    resultModificationController = new ResultModificationController();
    resultModificationListener = new ResultModificationEventExecutionLogListener(tenantContextFactory);

    final ApplicationEventPublisher applicationEventPublisher = new ApplicationEventPublisher() {
        @Override/*  w  ww .  jav a 2  s .com*/
        public void publishEvent(ApplicationEvent event) {
            resultModificationListener.onApplicationEvent((ResultModificationEvent) event);
        }
    };

    resultModificationController._contextFactory = tenantContextFactory;
    resultModificationController._resultDao = new ResultDaoImpl(tenantContextFactory,
            applicationEventPublisher);
}

From source file:org.springframework.amqp.rabbit.listener.DirectMessageListenerContainerTests.java

@Test
public void testEvents() throws Exception {
    CachingConnectionFactory cf = new CachingConnectionFactory("localhost");
    DirectMessageListenerContainer container = new DirectMessageListenerContainer(cf);
    container.setQueueNames(EQ1, EQ2);/*  w ww . ja v a  2 s  .co  m*/
    final List<Long> times = new ArrayList<>();
    final CountDownLatch latch1 = new CountDownLatch(2);
    final AtomicReference<ApplicationEvent> failEvent = new AtomicReference<>();
    final CountDownLatch latch2 = new CountDownLatch(2);
    container.setApplicationEventPublisher(new ApplicationEventPublisher() {

        @Override
        public void publishEvent(Object event) {
        }

        @Override
        public void publishEvent(ApplicationEvent event) {
            if (event instanceof ListenerContainerIdleEvent) {
                times.add(System.currentTimeMillis());
                latch1.countDown();
            } else {
                failEvent.set(event);
                latch2.countDown();
            }
        }

    });
    container.setMessageListener(m -> {
    });
    container.setIdleEventInterval(50L);
    container.setBeanName("events");
    container.setConsumerTagStrategy(new Tag());
    container.afterPropertiesSet();
    container.start();
    assertTrue(latch1.await(10, TimeUnit.SECONDS));
    assertThat(times.get(1) - times.get(0), greaterThanOrEqualTo(50L));
    brokerRunning.getAdmin().deleteQueue(EQ1);
    brokerRunning.getAdmin().deleteQueue(EQ2);
    assertTrue(latch2.await(10, TimeUnit.SECONDS));
    assertNotNull(failEvent.get());
    assertThat(failEvent.get(), instanceOf(ListenerContainerConsumerTerminatedEvent.class));
    container.stop();
    cf.destroy();
}

From source file:org.springframework.integration.file.tail.FileTailingMessageProducerTests.java

private void testGuts(FileTailingMessageProducerSupport adapter, String field) throws Exception {
    this.adapter = adapter;
    final List<FileTailingEvent> events = new ArrayList<FileTailingEvent>();
    adapter.setApplicationEventPublisher(new ApplicationEventPublisher() {
        @Override//from  w w  w .  j ava 2  s . com
        public void publishEvent(ApplicationEvent event) {
            FileTailingEvent tailEvent = (FileTailingEvent) event;
            logger.warn(event);
            events.add(tailEvent);
        }
    });
    adapter.setFile(new File(testDir, "foo"));
    QueueChannel outputChannel = new QueueChannel();
    adapter.setOutputChannel(outputChannel);
    adapter.setTailAttemptsDelay(500);
    adapter.afterPropertiesSet();
    File file = new File(testDir, "foo");
    File renamed = new File(testDir, "bar");
    file.delete();
    renamed.delete();
    adapter.start();
    waitForField(adapter, field);
    FileOutputStream foo = new FileOutputStream(file);
    for (int i = 0; i < 50; i++) {
        foo.write(("hello" + i + "\n").getBytes());
    }
    foo.flush();
    foo.close();
    for (int i = 0; i < 50; i++) {
        Message<?> message = outputChannel.receive(5000);
        assertNotNull("expected a non-null message", message);
        assertEquals("hello" + i, message.getPayload());
    }
    file.renameTo(renamed);
    file = new File(testDir, "foo");
    foo = new FileOutputStream(file);
    if (adapter instanceof ApacheCommonsFileTailingMessageProducer) {
        Thread.sleep(1000);
    }
    for (int i = 50; i < 100; i++) {
        foo.write(("hello" + i + "\n").getBytes());
    }
    foo.flush();
    foo.close();
    for (int i = 50; i < 100; i++) {
        Message<?> message = outputChannel.receive(10000);
        assertNotNull("expected a non-null message", message);
        assertEquals("hello" + i, message.getPayload());
    }
}

From source file:org.springframework.integration.ip.tcp.connection.CachingClientConnectionFactoryTests.java

private TcpConnectionSupport mockedTcpNetConnection() throws IOException {
    Socket socket = mock(Socket.class);
    when(socket.isClosed()).thenReturn(true); // closed when next retrieved
    OutputStream stream = mock(OutputStream.class);
    doThrow(new IOException("Foo")).when(stream).write(any(byte[].class), anyInt(), anyInt());
    when(socket.getOutputStream()).thenReturn(stream);
    TcpNetConnection conn = new TcpNetConnection(socket, false, false, new ApplicationEventPublisher() {

        @Override/*ww w  .  j  ava 2  s.c om*/
        public void publishEvent(ApplicationEvent event) {
        }

        @Override
        public void publishEvent(Object event) {

        }

    }, "foo");
    conn.setMapper(new TcpMessageMapper());
    conn.setSerializer(new ByteArrayCrLfSerializer());
    return conn;
}

From source file:org.springframework.integration.ip.tcp.connection.CachingClientConnectionFactoryTests.java

private TcpConnectionSupport mockedTcpNioConnection() throws Exception {
    SocketChannel socketChannel = mock(SocketChannel.class);
    new DirectFieldAccessor(socketChannel).setPropertyValue("open", false);
    doThrow(new IOException("Foo")).when(socketChannel).write(Mockito.any(ByteBuffer.class));
    when(socketChannel.socket()).thenReturn(mock(Socket.class));
    TcpNioConnection conn = new TcpNioConnection(socketChannel, false, false, new ApplicationEventPublisher() {

        @Override/*from  ww w.j  ava 2 s. c  om*/
        public void publishEvent(ApplicationEvent event) {
        }

        @Override
        public void publishEvent(Object event) {

        }

    }, "foo");
    conn.setMapper(new TcpMessageMapper());
    conn.setSerializer(new ByteArrayCrLfSerializer());
    return conn;
}