/** * Creates a new user with the specified name. * * @param username the name of the user * @param ensure {@code true} to return the user if it already exists, or {@code false} to throw an exception * @return the user * @throws UserAlreadyExistsException if the user already exists and {@code ensure} is {@code false} * @throws MetadataRepositoryException if the user could not be created */ @Nonnull private User createUser(@Nonnull final String username, final boolean ensure) { final Session session = getSession(); final String safeUserName = encodeUserName(username); final String userPath = UsersPaths.userPath(username).toString(); try { final Node usersNode = session.getRootNode().getNode(UsersPaths.USERS.toString()); if (session.getRootNode().hasNode(userPath)) { if (ensure) { return JcrUtil.getJcrObject(usersNode, safeUserName, JcrUser.class); } else { throw new UserAlreadyExistsException(username); } } else { return JcrUtil.getOrCreateNode(usersNode, safeUserName, JcrUser.NODE_TYPE, JcrUser.class); } } catch (RepositoryException e) { throw new MetadataRepositoryException("Failed attempting to create a new user with name: " + username, e); } }