Skip to content
Snippets Groups Projects
Commit b884f808 authored by Vilde Min Vikan's avatar Vilde Min Vikan
Browse files

Merge branch 'javadoc' into 'main'

Javadoc

See merge request !6
parents 6c7debff 469a873a
No related branches found
No related tags found
1 merge request!6Javadoc
Showing
with 423 additions and 68 deletions
......@@ -353,7 +353,7 @@ public class TrivioController {
long userId = Long.parseLong(jwtService.extractSubjectFromHeader(token));
Trivio trivio = trivioService.getTrivioById(trivioId);
if(userId == trivio.getUser().getId()){
trivioService.removeUserFromTrivio(trivioId, username);
trivioService.removeUserFromTrivioEditorList(trivioId, username);
return ResponseEntity.ok("User removed!");
}
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("User is not authorized to perform this action.");
......
......@@ -18,6 +18,15 @@ public class AuthenticationService {
this.passwordEncoder = passwordEncoder;
}
/**
* Method to authenticate a user and its login-request. The method checks the credentials in the
* login request and authenticate that the user-credentials are related to an exist the user repository.
* The method returns false as long as one of the credentials do not exist or is related to the same user as
* the other credentials.
*
* @param loginRequest the abstracted collection of user-credentials in a login-request (password and email).
* @return true or false based on if a user exist with all the parameters in the login-request.
*/
public boolean authenticateUser(LoginRequest loginRequest) {
//if user doesn't exist return false
if(!userService.checkIfUsernameIsPresent(loginRequest.getUsername())){
......@@ -28,6 +37,14 @@ public class AuthenticationService {
String encodedPassword = passwordEncoder.encode(user.getPassword());
return passwordEncoder.matches(loginRequest.getPassword(), encodedPassword);
}
/**
* Method to check if credentials in a signup-request exist. The method checks they exist in the
* user repository. The method return true as long as a one of the credentials exist.
*
* @param signUpRequest the abstracted collection of user-credentials in a signup-request (email and username)
* @return true or false depending on if the credentials exist.
*/
public boolean credentialsExists(SignUpRequest signUpRequest){
if(userService.checkIfUsernameIsPresent(signUpRequest.getUsername())){
return true;
......
......@@ -28,14 +28,24 @@ public class JWTService {
private String SECRET;
/**
* Method to get signing key by decoding the secret key with Base64 encoding.
*
* @return the signing key from the decoded secret key.
*/
private SecretKey getSigningKey() {
byte[] keyBytes = Base64.getDecoder().decode(this.SECRET.getBytes(StandardCharsets.UTF_8));
return Keys.hmacShaKeyFor(keyBytes);
}
/**
* Method to generate and build a token for a user. The method
* includes user as the subject of the token, and authenticate the token using the signing key.
*
* @param id the user-id for the user of the token.
* @return the generated token signed with the signing key.
*/
public String generateToken(String id){
logger.info(SECRET);
return Jwts.builder()
.subject(id)
.issuer("IDATT2105GROUP5")
......@@ -44,6 +54,13 @@ public class JWTService {
.signWith(getSigningKey())
.compact();
}
/**
* Method to parse token into claims.
*
* @param token the token to parse.
* @return the claims from the parsed token.
*/
public Jws<Claims> parseToken(String token) {
return Jwts.parser()
.verifyWith(getSigningKey())
......@@ -51,17 +68,45 @@ public class JWTService {
.parseSignedClaims(token);
}
/**
* Method to extract claims and get the payload from a token.
*
* @param token the token tro extract the claims from.
* @return the claims, payload from the token.
*/
public Claims extractClaims(String token) {
return parseToken(token).getPayload();
}
/**
* Method to extract the subject from claims, and identify the user from a token.
*
* @param token the token with the subject.
* @return the user-id for the user as a string.
*/
public String extractSubject(String token) {
return extractClaims(token).getSubject();
}
/**
* Method to validate an Authorization header bearing a token. This method
* ensures that the format is correct and that the header is not empty.
*
* @param header the authentication header to validate.
* @return true or false based on the validation of the header.
*/
public boolean checkValidHeader(String header){
return header != null && header.startsWith("Bearer ");
}
/**
* Collective method to extract the subject directly from an Authorization header. This
* method includes checking if the header is valid and extracting the subject, user from the
* token in the header.
*
* @param header the header to extract the subject from.
* @return the subject as a string. In this case the user-id as a string.
*/
public String extractSubjectFromHeader(String header){
if(!checkValidHeader(header)){
throw new IllegalArgumentException("Header is not valid!");
......
......@@ -16,10 +16,21 @@ public class MessageService {
this.messageRepository = messageRepository;
}
/**
* Method to create message and add it to the message repository,
*
* @param message the message to add to the repository.
* @return the status from the save method.
*/
public Message createMessage(Message message) {
return messageRepository.save(message);
}
/**
* Method to get all messages from the message repository.
*
* @return all messages as a list of messages from the repository.
*/
public List<Message> getAllMessages() {
return messageRepository.findAll();
}
......
......@@ -22,10 +22,22 @@ public class QuestionService {
this.answerRepository = answerRepository;
}
/**
* Method to add a question to the question repository.
*
* @param question the question to add to the repository.
*/
public void addQuestion(Question question) {
questionRepository.save(question);
}
/**
* Collective method to add a question with answers to the question repository,
* and answers to the answer repository.
*
* @param question the question to be added.
* @param answers the answers of the question to be added.
*/
@Transactional
public void addQuestionWithAnswers(Question question, List<Answer> answers) {
Question savedQuestion = questionRepository.save(question);
......@@ -35,12 +47,26 @@ public class QuestionService {
}
}
/**
* Collective method to delete a question with its answers from both repositories. The method do
* first delete all answers related to the question, and then the question. This should be
* on-delete-cascade.
*
* @param question the question to be deleted (containing the answers).
* @param answers the answers to be deleted.
*/
@Transactional
public void deleteQuestionWithAnswers(Question question, List<Answer> answers){
answerRepository.deleteAll(answers);
questionRepository.delete(question);
}
/**
* Method to get all questions related to a trivio, with all their answers.
*
* @param trivioId the id of the trivio containing the questions with the answers.
* @return the questions with answers in a list.
*/
public List<QuestionWithAnswers> getQuestionsWithAnswersByTrivioId(Long trivioId) {
List<Question> questions = questionRepository.findQuestionByTrivioId(trivioId);
......@@ -59,6 +85,11 @@ public class QuestionService {
return questionsWithAnswersByTrivioId;
}
/**
* Method to get all questions from the questions repository.
*
* @return all questions from the repository in a list.
*/
public List<Question> getAllQuestions(){
return questionRepository.findAll();
}
......
......@@ -24,31 +24,64 @@ public class ResultService {
this.trivioService = trivioService;
}
/**
* Method to add a DTO-abstracted result to the result repository. The method converts the
* abstraction to the result-entity and adds it to the repository.
*
* @param resultDTO the DTO-abstracted result to be added to the repository.
*/
public void addResult(ResultDTO resultDTO){
// per nå, ingen unntakshåndtering legg til det senere.
Result result = convertToEntity(resultDTO);
result.setPostedDate(new Date()); // Assign the current date/time
result.setPostedDate(new Date());
resultRepository.save(result);
}
//samme her!!
public Result getResultbyId(Long id){
/**
* Method to get a result by its result-id.
*
* @param id the result-id for the result.
* @return the result with the result-id.
*/
public Result getResultById(Long id){
if(resultRepository.findById(id).isPresent()) {
return resultRepository.findById(id).get();
}
return null;
}
/**
* Method to get results related to a user-id from the result repository.
* This method includes pagination.
*
* @param id the user-id for the user.
* @param pageable the page and max-number of results to retrieve.
* @return the method returns the chosen page with results related to the user-id.
*/
public Page<Result> getResultByUserId(Long id, Pageable pageable){
return resultRepository.getResultsByUserId(id, pageable);
}
/**
* Method to get results related to a user-id and trivio-title from the result repository.
* This method is used for result filtration and includes pagination.
*
* @param id the user-id for the user.
* @param title the title for the trivio.
* @param pageable the page and max-number of results to retrieve.
* @return the method returns the chosen page with results related to the user-id and trivio-title.
*/
public Page<Result> getResultByUserIdAndTitle(Long id, String title,Pageable pageable){
return resultRepository.getResultsByUserIdAndTrivio_Title(id, title,pageable);
}
/**
* Method to convert a result to a DTO-abstracted result containing the user, trivio and score relation.
*
* @param result the result to convert.
* @return the DTO-abstracted result.
*/
public ResultDTO convertToDTO(Result result){
Long trivioId = result.getTrivio().getId();
String username = result.getUser().getUsername();
......@@ -56,6 +89,12 @@ public class ResultService {
return new ResultDTO(username,score,trivioId);
}
/**
* Method to covert a DTO-abstracted result to a result entity with the user, trivio and score.
*
* @param resultDTO the DTO-abstracted result.
* @return the result entity of the abstraction.
*/
public Result convertToEntity(ResultDTO resultDTO){
User user = userService.getUserByUsername(resultDTO.getUsername());
Trivio trivio = trivioService.getTrivioById(resultDTO.getTrivioId());
......@@ -67,10 +106,21 @@ public class ResultService {
return result;
}
/**
* Method to get distinct trivio titles for a user from the result repository.
*
* @param userId the user-id for the user.
* @return the results as a list of string, distinct trivio titles in the repository.
*/
public List<String> getDistinctTrivioTitles(Long userId) {
return resultRepository.findDistinctTrivioTitlesByUserId(userId);
}
/**
* Method to get all results from the result repository.
*
* @return the results as a list of strings, all results from the repository.
*/
public List<Result> getAllResults(){
return resultRepository.findAll();
}
......
......@@ -26,13 +26,9 @@ public class TrivioService {
private final QuestionRepository questionRepository;
private final AnswerRepository answerRepository;
private final QuestionService questionService;
private final UserService userService;
private final JWTService jwtService;
private static final Logger logger = Logger.getLogger(TrivioService.class.getName());
@Autowired
public TrivioService(TrivioRepository trivioRepository, QuestionRepository questionRepository, QuestionService questionService,
AnswerRepository answerRepository, UserService userService, JWTService jwtService){
......@@ -44,43 +40,91 @@ public class TrivioService {
this.jwtService = jwtService;
}
/**
* Method to get all trivios. This method does not implement filtration.
*
* @return the list of all public trivios.
*/
public List<Trivio> getAllTrivios(){
return trivioRepository.findAll();
}
/**
* Method to get all public trivios. This method does not implement filtration.
*
* @return the list of all the public trivios.
*/
public List<Trivio> getAllPublicTrivios() {
return trivioRepository.findTrivioByVisibility("public");
}
/**
* Method to get all public trivios that is not linked to a user, meaning that they are
* owned and created by other users. This method does not implement filtration.
*
* @param userId user-id for the user.
* @return the list of public trivios that is not linked to the user.
*/
public List<Trivio> getAllPublicTriviosFromOtherUsers(long userId) {
return trivioRepository.findTrivioByVisibilityAndUserIdNot("public", userId);
}
/**
* Method to get trivios by a user. This method does not implement filtration.
*
* @param userId the user-id of the user
* @return the list of trivios belonging to this user.
*/
public List<Trivio> getTriviosByUserId(Long userId){
return trivioRepository.findTrivioByUserId(userId);
}
public void deleteTrivio(Long id){
Trivio trivio = getTrivioById(id);
trivioRepository.delete(trivio);
}
/**
* Method to retrieve a trivio by its trivio-id.
*
* @param id the id of the trivio to retrieve.
* @return returning the trivio if present.
*/
public Trivio getTrivioById(Long id){
return trivioRepository.findById(id).orElseThrow(() -> new TrivioNotFoundException(id));
}
/**
* Method to retrieve a trivio by its title.
* @param title the title of the trivio.
* @return returning the trivio if present.
*/
public Trivio getTrivioByTitle(String title){
if(trivioRepository.findTrivioByTitle(title).isPresent()){
return trivioRepository.findTrivioByTitle(title).get();
}
return null;
return trivioRepository.findTrivioByTitle(title).orElseThrow(()
-> new RuntimeException("Title do not exist in the repository"));
}
/**
* Method to check if a user is the owner of a trivio.
*
* @param token the token that belong to the user.
* @param id the trivio-id of the trivio.
* @return true-false statement weather the user is the owner or not.
*/
public boolean checkIfUserIsOwner(String token, Long id){
try {
Trivio trivio = getTrivioById(id);
long userId = Long.parseLong(jwtService.extractSubjectFromHeader(token));
if(userId == trivio.getUser().getId()){
return true;
} else throw new RuntimeException("The user is not authorized to modify the trivio");
return userId == trivio.getUser().getId();
} catch (Exception e){
throw new RuntimeException(e.getMessage());
}
}
/**
* Method to create a trivio with a user.
*
* @param trivioWithQAndA trivio with questions and answers.
* @param userId the user-id of the creator.
*/
@Transactional
public void createTrivio(TrivioWithQAndA trivioWithQAndA, Long userId){
try {
Trivio trivio = trivioWithQAndA.getTrivio();
......@@ -104,36 +148,54 @@ public class TrivioService {
}
}
/**
* Method to edit a trivio. The method should ideally be more split up into multiple services.
* Se inline comments for more description of functionally.
*
* @param editedTrivioWithQAndA the trivio with questions and answers that contain the updated information.
* @param trivioId the trivio-id of the trivio to edit.
*/
@Transactional
public void editTrivio(TrivioWithQAndA editedTrivioWithQAndA, long trivioId) {
try {
Trivio trivio = trivioRepository.findById(trivioId).orElseThrow(() -> new TrivioNotFoundException(trivioId));
Trivio newTrivioInfo = editedTrivioWithQAndA.getTrivio();
//editing all the basic trivio information;
try {
trivio.setTitle(newTrivioInfo.getTitle());
trivio.setDescription(newTrivioInfo.getDescription());
trivio.setCategory(newTrivioInfo.getCategory());
trivio.setDifficulty(newTrivioInfo.getDifficulty());
trivio.setVisibility(newTrivioInfo.getVisibility());
trivio.setMultimedia_url(newTrivioInfo.getMultimedia_url());
} catch(Exception e){
throw new RuntimeException("Something went wrong when updating the trivio information: " + e.getMessage());
}
List<QuestionWithAnswers> newQuestionsWithAnswers = editedTrivioWithQAndA.getQuestionsWithAnswers();
List<QuestionWithAnswers> existingQuestionsWithAnswers = questionService.getQuestionsWithAnswersByTrivioId(trivioId);
//calculating the number of overlapping questions.
int questionMinSize = Math.min(newQuestionsWithAnswers.size(), existingQuestionsWithAnswers.size());
//updating all overlapping questions in the new and old list of questions.
for(int i=0; i < questionMinSize; i++) {
QuestionWithAnswers newQuestionWithAnswers = newQuestionsWithAnswers.get(i);
QuestionWithAnswers oldQuestionWithAnswers = existingQuestionsWithAnswers.get(i);
oldQuestionWithAnswers.getQuestion().setQuestionType(newQuestionWithAnswers.getQuestion().questionType);
oldQuestionWithAnswers.getQuestion().setQuestion(newQuestionWithAnswers.getQuestion().question);
oldQuestionWithAnswers.getQuestion().setTags(newQuestionWithAnswers.getQuestion().tags);
oldQuestionWithAnswers.getQuestion().setMedia(newQuestionWithAnswers.getQuestion().media);
List<Answer> newAnswers = newQuestionWithAnswers.getAnswers();
List<Answer> oldAnswers = oldQuestionWithAnswers.getAnswers();
//calculating the number of overlapping answers
int answerMinSize = Math.min(oldAnswers.size(), newAnswers.size());
//updating all overlapping questions in the new and old list of answers.
for(int j=0; j < answerMinSize; j++){
Answer newAnswer = newAnswers.get(j);
Answer oldAnswer = oldAnswers.get(j);
......@@ -144,7 +206,7 @@ public class TrivioService {
answerRepository.save(oldAnswer);
}
//if the question is changed from true-false to multiple
//if the question is changed from true-false to multiple, then more answers need to be added.
if(newAnswers.size() > oldAnswers.size()){
for(int j = answerMinSize; j < newAnswers.size(); j++){
Answer newAnswer = newAnswers.get(j);
......@@ -153,7 +215,7 @@ public class TrivioService {
}
}
//if the question is changed from multiple to true-false
//if the question is changed from multiple to true-false, then some answers need to be removed.
if(newAnswers.size() < oldAnswers.size()){
for(int j = answerMinSize; j < oldAnswers.size(); j++){
answerRepository.delete(oldAnswers.get(j));
......@@ -162,7 +224,7 @@ public class TrivioService {
questionRepository.save(oldQuestionWithAnswers.getQuestion());
}
//if more questions are added to the trivio
//if the new question-list is longer than the old question-list, more questions are added to the trivio
if(newQuestionsWithAnswers.size() > existingQuestionsWithAnswers.size()){
for(int i = questionMinSize; i < newQuestionsWithAnswers.size(); i++){
Question newQuestion = newQuestionsWithAnswers.get(i).getQuestion();
......@@ -172,7 +234,7 @@ public class TrivioService {
}
}
//if some questions are removed from the trivio
//if the new question-list is shorter than the old question-list, some questions are removed from the trivio.
if(newQuestionsWithAnswers.size() < existingQuestionsWithAnswers.size()){
for(int i = questionMinSize; i < existingQuestionsWithAnswers.size(); i++){
Question existingQuestion = existingQuestionsWithAnswers.get(i).getQuestion();
......@@ -183,8 +245,21 @@ public class TrivioService {
trivioRepository.save(trivio); // Save the updated trivio
} catch (Exception e) {
// Handle the exception appropriately
e.printStackTrace(); // Log the exception stack trace
throw new RuntimeException(e.getMessage());
}
}
/**
* Method to delete a trivio from the trivio-repository.
*
* @param id the id of the trivio to delete.
*/
public void deleteTrivio(Long id){
try {
Trivio trivio = getTrivioById(id);
trivioRepository.delete(trivio);
} catch (Exception e){
throw new RuntimeException(e.getMessage());
}
}
......@@ -194,22 +269,50 @@ public class TrivioService {
return trivio.getUsersThatCanEdit();
}
/**
* Method to add a user to a trivios editor-list. This means that the user is able to
* edit the trivio, even though it do not belong to the user.
*
* @param trivioId the trivio-id of the trivio.
* @param username the username of the user to add to the trivios editor-list.
*/
public void addUserToTrivio(Long trivioId, String username) {
Trivio trivio = trivioRepository.findById(trivioId).orElseThrow(() -> new EntityNotFoundException("Trivio not found"));
try {
Trivio trivio = getTrivioById(trivioId);
User user = userService.getUserByUsername(username);
logger.info("I reached to addUserToTrivio");
logger.info(user.getUsername());
trivio.addUserThatCanEdit(user);
trivioRepository.save(trivio); // This will update the trivio and the join table
} catch (Exception e){
throw new RuntimeException(e.getMessage());
}
}
public void removeUserFromTrivio(Long trivioId, String username) {
Trivio trivio = trivioRepository.findById(trivioId).orElseThrow(() -> new EntityNotFoundException("Trivio not found"));
/**
* Method to remove a remove user from a trivios editor-list. This means that the user
* is no longer able to edit the previously shared trivio.
*
* @param trivioId the trivio-id of the trivio.
* @param username the username of the user to remove.
*/
public void removeUserFromTrivioEditorList(Long trivioId, String username) {
try {
Trivio trivio = getTrivioById(trivioId);
User user = userService.getUserByUsername(username);
trivio.removeUserThatCanEdit(user);
trivioRepository.save(trivio); // This will update the trivio and the join table
} catch (Exception e){
throw new RuntimeException(e.getMessage());
}
}
/**
* Method to check if a trivio is shared with a user. The method checks if the user exists
* in the list of users that can edit the trivio.
*
* @param trivio the trivio that is or is not shared with the user.
* @param userId the user-id of the user that can or cannot edit the trivio.
* @return true if the trivio is shared with the user, or false if not.
*/
public boolean isUserInListCanEdit(Trivio trivio, long userId) {
List<User> usersThatCanEdit = trivio.getUsersThatCanEdit();
if (usersThatCanEdit != null) {
......@@ -222,6 +325,18 @@ public class TrivioService {
return false;
}
/**
* Method to retrieve public trivios that do not belong to a user. If any filter alternatives are added,
* then the method will retrieve the filtrated result from the repository. The method includes pagination. Filter methods
* are specified in the TrivioSpecification class.
*
* @param userId the user-id of the user that the public trivios do not belong to.
* @param category the category for filtration.
* @param difficulty the difficulty for filtration.
* @param tags the tags for filtration.
* @param pageable the page and max-number of trivios to retrieve.
* @return the method returns the chosen page with public trivios that do not belong to the user.
*/
public Page<Trivio> getFilteredPublicTriviosByOtherUsers(
Long userId, String category, String difficulty,
List<String> tags, String visibility, Pageable pageable) {
......@@ -230,17 +345,17 @@ public class TrivioService {
spec = spec.and(TrivioSpecifications.filterByVisibility(visibility));
//If no category is chosen
//If a category is chosen
if (category != null) {
spec = spec.and(TrivioSpecifications.filterByCategory(category));
}
//If no difficulty is chosen
//If a difficulty is chosen
if (difficulty != null) {
spec = spec.and(TrivioSpecifications.filterByDifficulty(difficulty));
}
//If no tags are chosen
//If a tags are chosen
if (tags != null && !tags.isEmpty()) {
spec = spec.and(TrivioSpecifications.filterByTags(tags));
}
......@@ -248,20 +363,32 @@ public class TrivioService {
return trivioRepository.findAll(spec, pageable);
}
/**
* Method to retrieve trivios that belong to a user from the trivio repository. If any filter alternatives are added,
* then the method will retrieve the filtrated result from the repository. The method includes pagination. Filter methods
* are specified in the TrivioSpecification class.
*
* @param userId the user-id of the user that the trivios belong to.
* @param category the category for filtration.
* @param difficulty the difficulty for filtration.
* @param tags the tags for filtration.
* @param pageable the page and max-number of trivios to retrieve.
* @return the method returns the chosen page with trivios that belong to the user.
*/
public Page<Trivio> getFilteredTriviosByUser(Long userId, String category, String difficulty, List<String> tags, Pageable pageable) {
Specification<Trivio> spec = TrivioSpecifications.filterByUserId(userId);
//If no category is chosen
//If a category is chosen
if (category != null) {
spec = spec.and(TrivioSpecifications.filterByCategory(category));
}
//If no difficulty is chosen
//If a difficulty is chosen
if (difficulty != null) {
spec = spec.and(TrivioSpecifications.filterByDifficulty(difficulty));
}
//If no tags are chosen.
//If a tags are chosen.
if (tags != null && !tags.isEmpty()) {
spec = spec.and(TrivioSpecifications.filterByTags(tags));
}
......@@ -269,20 +396,32 @@ public class TrivioService {
return trivioRepository.findAll(spec, pageable);
}
/**
* Method to retrieve trivios that is shared with a user from the trivio repository. If any filter alternatives are added,
* then the method will retrieve the filtrated result from the repository. The method includes pagination. Filter methods are
* specified in the TrivioSpecification class.
*
* @param userId the user-id of the user that the trivios are shared with.
* @param category the category for filtration.
* @param difficulty the difficulty for filtration.
* @param tags the tags for filtration.
* @param pageable the page and max-number of trivios to retrieve.
* @return the method returns the chosen page with trivios that are shared with the user.
*/
public Page<Trivio> getFilteredSharedTriviosByUser(Long userId, String category, String difficulty, List<String> tags, Pageable pageable) {
Specification<Trivio> spec = TrivioSpecifications.filterByUserInSharedList(userId);
//If no category is chosen
//If category is chosen, add filter method from trivio-specifications
if (category != null) {
spec = spec.and(TrivioSpecifications.filterByCategory(category));
}
//If no difficulty is chosen
//If difficulty is chosen, add filter method from trivio-specifications
if (difficulty != null) {
spec = spec.and(TrivioSpecifications.filterByDifficulty(difficulty));
}
//If no tags are chosen.
//If tags are chosen, add filter method from trivio-specifications
if (tags != null && !tags.isEmpty()) {
spec = spec.and(TrivioSpecifications.filterByTags(tags));
}
......
......@@ -6,9 +6,14 @@ import ntnu.idatt2105.group44.trivioServer.model.Trivio;
import org.springframework.data.jpa.domain.Specification;
import java.util.List;
/**
* Class containing trivio-specifications for retrieving more
* detailed and customized queries.
*/
public class TrivioSpecifications {
//Method to filter trivios by user-id
//Method to specify filter trivios by user-id
public static Specification<Trivio> filterByUserId(Long userId) {
return (root, query, criteriaBuilder) ->
criteriaBuilder.equal(root.get("user").get("id"), userId);
......
......@@ -25,20 +25,42 @@ public class UserService {
this.userRepository = userRepository;
}
/**
* Method to get a user by its user-id from the user repository.
*
* @param id the id of the user.
* @return the user from the repository or not-found exception if user is not found.
*/
public User getUserById(Long id){
Optional<User> userOptional = userRepository.findById(id);
return userOptional.orElseThrow(() -> new UserNotFoundException(id));
}
/**
* Method to get a user by its username from the user repository.
*
* @param username the username of the user.
* @return the user from the repository or not-found exception if user is not found.
*/
public User getUserByUsername(String username){
Optional<User> userOptional = userRepository.findUserByUsername(username);
return userOptional.orElseThrow(() -> new UserNotFoundException(username));
}
/**
* Method to get all users from the user repository.
*
* @return all users in the user repository.
*/
public List<User> getAllUsers(){
return userRepository.findAll();
}
/**
* Method to create a user from a signup-request.
*
* @param signUpRequest the signup-request containing user information.
*/
public void createUser(SignUpRequest signUpRequest){
if(signUpRequest.getUsername() != null && signUpRequest.getEmail() != null && signUpRequest.getPassword() != null){
User user = new User.Builder()
......@@ -51,6 +73,13 @@ public class UserService {
}
}
/**
* Method to update an existing user with new information.
*
* @param username the new username.
* @param email the new email.
* @param userId the user-id for the user that is updated.
*/
@Transactional
public void updateUser(String username, String email, Long userId){
User user = getUserById(userId);
......@@ -65,6 +94,13 @@ public class UserService {
}
/**
* Method to check if a username exists in the user repository,
* and if not present, update a user with the username.
*
* @param newUsername the new username value.
* @param user the username of the user to be updated.
*/
private void checkAndUpdateUsername(String newUsername, User user) {
if (checkIfUsernameIsPresent(newUsername)) {
throw new UserAlreadyExistException("Username already exists!");
......@@ -73,12 +109,26 @@ public class UserService {
user.setUsername(newUsername);
}
/**
* Method to check if an email exists in the user repository,
* and if not present, update a user with the username.
*
* @param newEmail the new email value.
* @param user the username of the user to be updated.
*/
private void checkAndUpdateEmail(String newEmail, User user) {
if (checkIfEmailIsPresent(newEmail)) {
throw new UserAlreadyExistException("Email is already taken!");
}
user.setEmail(newEmail);
}
/**
* Method to update an existing user with a new password. The password cannot be blank.
*
* @param password the new password value.
* @param userId the user-id for the user to be updated.
*/
@Transactional
public void updatePassword(String password, Long userId){
User user = getUserById(userId);
......@@ -87,16 +137,23 @@ public class UserService {
}
userRepository.save(user);
}
//Validation of user should happen in the authentication service
// public boolean validateUser(String username, String password) {
// Optional<User> user = userRepository.findUserByUsername(username);
// return user.isPresent() && user.get().getPassword().equals(password);
// }
/**
* Method to check if a username is present in the user repository.
*
* @param name the username.
* @return true-false statement for if the username is present.
*/
public boolean checkIfUsernameIsPresent(String name){
return userRepository.findUserByUsername(name).isPresent();
}
/**
* Method to check if an email is present in the user repository,
*
* @param email the email
* @return true-false statement for if the email is present.
*/
public boolean checkIfEmailIsPresent(String email){
return userRepository.findUserByEmail(email).isPresent();
}
......
......@@ -55,7 +55,7 @@ class ResultServiceTest {
when(resultRepository.findById(5L)).thenReturn(java.util.Optional.of(result));
Result foundResult = resultService.getResultbyId(5L);
Result foundResult = resultService.getResultById(5L);
verify(resultRepository, times(2)).findById(5L);
......@@ -66,7 +66,7 @@ class ResultServiceTest {
void testGetResultByIdReturnNull() {
when(resultRepository.findById(5L)).thenReturn(java.util.Optional.empty());
Result foundResult = resultService.getResultbyId(5L);
Result foundResult = resultService.getResultById(5L);
verify(resultRepository, times(1)).findById(5L);
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment