AdminUserCreator implements EventSubscriber<PostUserPersistedEvent> { @PostConstruct public void create() throws ServerException { boolean shouldCreateAdmin = true; if (LdapAuthenticationHandler.TYPE.equals(authHandler)) { eventService.subscribe(this); shouldCreateAdmin = false; } try { User adminUser = userManager.getByName(name); grantSystemPermissions(adminUser.getId()); } catch (NotFoundException ex) { if (shouldCreateAdmin) { try { User adminUser = userManager.create(new UserImpl(name, email, name, password, emptyList()), false); grantSystemPermissions(adminUser.getId()); LOG.info("Admin user '" + name + "' successfully created"); } catch (ConflictException cfEx) { LOG.warn("Admin user creation failed", cfEx.getLocalizedMessage()); } } } }  @PostConstruct void create(); @PreDestroy void unsubscribe(); @Override void onEvent(PostUserPersistedEvent event);  }
@Test public void shouldCreateAdminUser() throws Exception { Injector injector = Guice.createInjector(new OrgModule()); UserManager userManager = injector.getInstance(UserManager.class); when(userManager.getByName(NAME)).thenThrow(new NotFoundException("nfex")); when(userManager.create(any(UserImpl.class), anyBoolean())).thenReturn(user); injector.getInstance(AdminUserCreator.class); verify(userManager).getByName(NAME); verify(userManager).create(new UserImpl(NAME, EMAIL, NAME, PASSWORD, emptyList()), false); verify(permissionsManager) .storePermission( argThat( (ArgumentMatcher<SystemPermissionsImpl>) argument -> argument.getUserId().equals("qwe"))); }
@Test public void shouldNotCreateAdminWhenItAlreadyExists() throws Exception { final UserImpl user = new UserImpl(NAME, EMAIL, NAME, PASSWORD, emptyList()); Injector injector = Guice.createInjector(new OrgModule()); UserManager userManager = injector.getInstance(UserManager.class); when(userManager.getByName(NAME)).thenReturn(user); injector.getInstance(AdminUserCreator.class); verify(userManager).getByName(NAME); verify(userManager, times(0)).create(user, false); }