UserManagementServiceImpl implements UserManagementService { @POST @Override public Response addUser(UserInfo userInfo) { try { UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); if (userStoreManager.isExistingUser(userInfo.getUsername())) { if (log.isDebugEnabled()) { log.debug("User by username: " + userInfo.getUsername() + " already exists. Therefore, request made to add user was refused."); } return Response.status(Response.Status.CONFLICT).entity( new ErrorResponse.ErrorResponseBuilder().setMessage("User by username: " + userInfo.getUsername() + " already exists. Therefore, request made to add user " + "was refused.").build()).build(); } String initialUserPassword = this.generateInitialUserPassword(); Map<String, String> defaultUserClaims = this.buildDefaultUserClaims(userInfo.getFirstname(), userInfo.getLastname(), userInfo.getEmailAddress()); List<String> tmpRoles = new ArrayList<>(); String[] userInfoRoles = userInfo.getRoles(); tmpRoles.add(DEFAULT_DEVICE_USER); if (userInfoRoles != null) { tmpRoles.addAll(Arrays.asList(userInfoRoles)); } String[] roles = new String[tmpRoles.size()]; tmpRoles.toArray(roles); if (!userStoreManager.isExistingRole(DEFAULT_DEVICE_USER)) { userStoreManager.addRole(DEFAULT_DEVICE_USER, null, PERMISSIONS_FOR_DEVICE_USER); } userStoreManager.addUser(userInfo.getUsername(), initialUserPassword, roles, defaultUserClaims, null); if (log.isDebugEnabled()) { log.debug("User '" + userInfo.getUsername() + "' has successfully been added."); } BasicUserInfo createdUserInfo = this.getBasicUserInfo(userInfo.getUsername()); if (log.isDebugEnabled()) { log.debug("User by username: " + userInfo.getUsername() + " was found."); } DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService(); String[] bits = userInfo.getUsername().split("/"); String username = bits[bits.length - 1]; String recipient = userInfo.getEmailAddress(); Properties props = new Properties(); props.setProperty("first-name", userInfo.getFirstname()); props.setProperty("last-name", userInfo.getLastname()); props.setProperty("username", username); props.setProperty("password", initialUserPassword); EmailMetaInfo metaInfo = new EmailMetaInfo(recipient, props); BasicUserInfoWrapper userInfoWrapper = new BasicUserInfoWrapper(); String message; try { dms.sendRegistrationEmail(metaInfo); message = "An invitation mail will be sent to this user to initiate device enrollment."; } catch (ConfigurationManagementException e) { message = "Mail Server is not configured. Email invitation will not be sent."; } userInfoWrapper.setBasicUserInfo(createdUserInfo); userInfoWrapper.setMessage(message); return Response.created(new URI(API_BASE_PATH + "/" + URIEncoder.encode(userInfo.getUsername(), "UTF-8"))).entity(userInfoWrapper).build(); } catch (UserStoreException e) { String msg = "Error occurred while trying to add user '" + userInfo.getUsername() + "' to the " + "underlying user management system"; log.error(msg, e); return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } catch (URISyntaxException e) { String msg = "Error occurred while composing the location URI, which represents information of the " + "newly created user '" + userInfo.getUsername() + "'"; log.error(msg, e); return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } catch (UnsupportedEncodingException e) { String msg = "Error occurred while encoding username in the URI for the newly created user " + userInfo.getUsername(); log.error(msg, e); return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } catch (DeviceManagementException e) { String msg = "Error occurred while sending registration email to the user " + userInfo.getUsername(); log.error(msg, e); return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } }  @POST @Override Response addUser(UserInfo userInfo); @GET @Path("/{username}") @Override Response getUser(@PathParam("username") String username, @QueryParam("domain") String domain,
                            @HeaderParam("If-Modified-Since") String ifModifiedSince); @PUT @Path("/{username}") @Override Response updateUser(@PathParam("username") String username, @QueryParam("domain") String domain, UserInfo userInfo); @DELETE @Path("/{username}") @Override Response removeUser(@PathParam("username") String username, @QueryParam("domain") String domain); @GET @Path("/{username}/roles") @Override Response getRolesOfUser(@PathParam("username") String username, @QueryParam("domain") String domain); @GET @Override Response getUsers(@QueryParam("filter") String filter, @HeaderParam("If-Modified-Since") String timestamp,
                             @QueryParam("offset") int offset,
                             @QueryParam("limit") int limit); @GET @Path("/count") @Override Response getUserCount(); @GET @Path("/checkUser") @Override Response isUserExists(@QueryParam("username") String userName); @GET @Path("/search/usernames") @Override Response getUserNames(@QueryParam("filter") String filter, @QueryParam("domain") String domain,
                                 @HeaderParam("If-Modified-Since") String timestamp,
                                 @QueryParam("offset") int offset, @QueryParam("limit") int limit); @PUT @Path("/credentials") @Override Response resetPassword(OldPasswordResetWrapper credentials); @POST @Path("/send-invitation") @Produces({MediaType.APPLICATION_JSON}) Response inviteExistingUsersToEnrollDevice(List<String> usernames); @POST @Path("/enrollment-invite") @Override Response inviteToEnrollDevice(EnrollmentInvitation enrollmentInvitation);  }
@Test(description = "This method tests the addUser method of UserManagementService") public void testAddUser() throws UserStoreException, ConfigurationManagementException, DeviceManagementException { PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getUserStoreManager")) .toReturn(this.userStoreManager); PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService")) .toReturn(this.deviceManagementProviderService); Mockito.doReturn(true).when(userStoreManager).isExistingUser("admin"); Mockito.doAnswer(new Answer() { private int count = 0; public Object answer(InvocationOnMock invocation) { if (count == 0) { count++; return false; } else { return true; } } }).when(userStoreManager).isExistingUser(TEST_USERNAME); Mockito.doReturn("test@test.com").when(userStoreManager) .getUserClaimValue(TEST_USERNAME, Constants.USER_CLAIM_EMAIL_ADDRESS, null); Mockito.doReturn(TEST_USERNAME).when(userStoreManager) .getUserClaimValue(TEST_USERNAME, Constants.USER_CLAIM_FIRST_NAME, null); Mockito.doReturn(TEST_USERNAME).when(userStoreManager) .getUserClaimValue(TEST_USERNAME, Constants.USER_CLAIM_LAST_NAME, null); Mockito.doNothing().when(userStoreManager) .addUser(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); UserInfo userInfo = new UserInfo(); userInfo.setUsername("admin"); Response response = userManagementService.addUser(userInfo); Assert.assertEquals(response.getStatus(), Response.Status.CONFLICT.getStatusCode(), "Same user can be added " + "twice"); userInfo = getUserInfo(); Mockito.doReturn(true).when(userStoreManager).isExistingRole(DEFAULT_DEVICE_USER); Mockito.doNothing().when(deviceManagementProviderService).sendRegistrationEmail(Mockito.any()); response = userManagementService.addUser(userInfo); Assert.assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode(), "User addition failed"); }