Skip to content
Snippets Groups Projects
Commit 13976d4b authored by Torbjørn Antonsen's avatar Torbjørn Antonsen
Browse files

Merge branch 'addition' into 'main'

javadoc and testclasses for backend

See merge request !37
parents 79d0501d 4327b1b0
Branches
No related tags found
1 merge request!37javadoc and testclasses for backend
Pipeline #269506 passed
Showing
with 767 additions and 96 deletions
......@@ -59,13 +59,23 @@
<artifactId>jjwt-jackson</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.7.0</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.5.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
......
......@@ -4,8 +4,17 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* Configuration class for CORS (Cross-Origin Resource Sharing).
*/
@Configuration
public class CorsConfig implements WebMvcConfigurer {
/**
* Adds CORS mapping configuration.
*
* @param registry CorsRegistry instance to configure CORS mappings.
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
......
......@@ -26,16 +26,28 @@ import org.springframework.security.oauth2.server.resource.authentication.JwtAut
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;
import org.springframework.security.web.SecurityFilterChain;
/**
* Configuration class for Security.
*/
@Configuration
public class SecurityConfiguration {
private final RSAKeyProperties keys;
/**
* Constructor for SecurityConfiguration.
* @param keys RSAKeyProperties instance for handling RSA keys.
*/
public SecurityConfiguration(RSAKeyProperties keys) {
this.keys = keys;
}
/**
* Configures the AuthenticationManager bean.
* @param userDetailsService UserDetailsService instance for managing user details.
* @param encoder PasswordEncoder instance for encoding passwords.
* @return AuthenticationManager instance.
*/
@Bean
public AuthenticationManager authenticationManager(UserDetailsService userDetailsService, PasswordEncoder encoder) {
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
......@@ -43,17 +55,30 @@ public class SecurityConfiguration {
daoAuthenticationProvider.setPasswordEncoder(encoder);
return new ProviderManager(daoAuthenticationProvider);
}
/**
* Configures the PasswordEncoder bean.
* @return PasswordEncoder instance.
*/
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
/**
* Configures the SecurityFilterChain bean.
* @param httpSecurity HttpSecurity instance for configuring security settings.
* @return SecurityFilterChain instance.
* @throws Exception Exception thrown for configuration errors.
*/
@Bean
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(auth -> {
auth.requestMatchers("/api/**").permitAll();
auth.requestMatchers("/api/**",
"/v3/api-docs/",
"/swagger-ui/").permitAll();
auth.anyRequest().authenticated();
})
......@@ -66,11 +91,19 @@ public class SecurityConfiguration {
.build();
}
/**
* Configures the JwtDecoder bean.
* @return JwtDecoder instance.
*/
@Bean
public JwtDecoder jwtDecoder() {
return NimbusJwtDecoder.withPublicKey(keys.getPublicKey()).build();
}
/**
* Configures the JwtEncoder bean.
* @return JwtEncoder instance.
*/
@Bean
public JwtEncoder jwtEncoder() {
JWK jwk = new RSAKey.Builder(keys.getPublicKey()).privateKey(keys.getPrivateKey()).build();
......@@ -78,6 +111,10 @@ public class SecurityConfiguration {
return new NimbusJwtEncoder(jwkSource);
}
/**
* Configures the JwtAuthenticationConverter bean.
* @return JwtAuthenticationConverter instance.
*/
@Bean
public JwtAuthenticationConverter jwtAuthenticationConverter() {
JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
......@@ -90,6 +127,3 @@ public class SecurityConfiguration {
return jwtAuthenticationConverter;
}
}
package edu.ntnu.idatt2105.controller;
import edu.ntnu.idatt2105.dto.LoginResponseDTO;
import edu.ntnu.idatt2105.dto.TokenDTO;
import edu.ntnu.idatt2105.dto.UserRegistrationDTO;
......@@ -10,8 +9,9 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
/**
* Controller class responsible for handling authentication-related API endpoints.
*/
@RestController
@RequestMapping("/api/auth")
public class AuthenticationController {
......@@ -19,22 +19,46 @@ public class AuthenticationController {
private final AuthenticationService authService;
private static final Logger logger = LoggerFactory.getLogger(AuthenticationController.class);
/**
* Constructor for AuthenticationController.
*
* @param authService An instance of AuthenticationService used for user authentication.
*/
public AuthenticationController(AuthenticationService authService) {
this.authService = authService;
}
/**
* Endpoint for user registration.
*
* @param registrationDTO The registration data for the new user.
* @return The newly registered user.
*/
@PostMapping("/register")
public User registerUser(@RequestBody UserRegistrationDTO registrationDTO) {
// TODO: Remove return of password, use DTO
return authService.registerUser(registrationDTO.getUsername(), registrationDTO.getPassword());
}
/**
* Endpoint for user login.
*
* @param registrationDTO The login data for the user.
* @return The login response containing authentication token.
*/
@PostMapping("/login")
public LoginResponseDTO loginUser(@RequestBody UserRegistrationDTO registrationDTO) {
logger.info("Logging in with user " + registrationDTO.toString());
return authService.loginUser(registrationDTO.getUsername(), registrationDTO.getPassword());
}
/**
* Endpoint for refreshing JWT token.
*
* @param existingToken The existing JWT token.
* @return The refreshed JWT token.
* @throws InterruptedException If interrupted while sleeping.
*/
@PostMapping("/refresh")
public TokenDTO refreshJWT(@RequestBody TokenDTO existingToken) throws InterruptedException {
Thread.sleep(500);
......
......@@ -13,19 +13,35 @@ import org.springframework.web.bind.annotation.*;
import java.util.Optional;
/**
* Controller class responsible for handling question-answer related endpoints.
*/
@RestController
@RequestMapping("/question-answers")
public class QuestionAnswerController {
private final QuestionAnswerService questionAnswerService;
private QuestionService questionService;
private final QuestionService questionService;
/**
* Constructor for QuestionAnswerController.
*
* @param questionAnswerService An instance of QuestionAnswerService used for managing question answers.
* @param questionService An instance of QuestionService used for managing questions.
*/
@Autowired
public QuestionAnswerController(QuestionAnswerService questionAnswerService, QuestionService questionService) {
this.questionAnswerService = questionAnswerService;
this.questionService = questionService;
}
/**
* Endpoint for saving a user's answer to a question.
*
* @param quizResultId The ID of the quiz result.
* @param answerDTO The answer provided by the user.
* @return The saved question answer DTO.
*/
@PostMapping("/save")
public QuestionAnswerDTO saveAnswer(@RequestParam Integer quizResultId,
@RequestBody QuestionAnswerDTO answerDTO) {
......@@ -33,12 +49,24 @@ public class QuestionAnswerController {
return convertToQuestionAnswerDTO(savedAnswer);
}
@GetMapping("/is-correct")
public ResponseEntity<Boolean> isCorrect(@RequestBody QuestionAnswerDTO answerDTO) {
boolean correct = questionAnswerService.isCorrect(convertToQuestionAnswer(answerDTO));
/**
* Endpoint for checking if a question answer is correct.
*
* @param questionAnswerId The ID of the question answer.
* @return A ResponseEntity containing a boolean indicating whether the answer is correct or not.
*/
@GetMapping("/is-correct/{questionAnswerId}")
public ResponseEntity<Boolean> isCorrect(@PathVariable Integer questionAnswerId) {
boolean correct = questionAnswerService.isCorrect(questionAnswerId);
return new ResponseEntity<>(correct, HttpStatus.OK);
}
/**
* Converts a QuestionAnswer entity to a QuestionAnswerDTO.
*
* @param questionAnswer The QuestionAnswer entity to convert.
* @return The converted QuestionAnswerDTO.
*/
private QuestionAnswerDTO convertToQuestionAnswerDTO(QuestionAnswer questionAnswer) {
QuestionAnswerDTO dto = new QuestionAnswerDTO();
dto.setId(questionAnswer.getId());
......@@ -48,6 +76,13 @@ public ResponseEntity<Boolean> isCorrect(@RequestBody QuestionAnswerDTO answerDT
return dto;
}
/**
* Converts a QuestionAnswerDTO to a QuestionAnswer entity.
*
* @param questionAnswerDTO The QuestionAnswerDTO to convert.
* @return The converted QuestionAnswer entity.
* @throws QuestionNotFoundException If the associated question is not found.
*/
private QuestionAnswer convertToQuestionAnswer(QuestionAnswerDTO questionAnswerDTO) {
Optional<Question> questionOptional = Optional.ofNullable(questionService.findQuestionById(questionAnswerDTO.getQuestionId()));
Question question = questionOptional.orElseThrow(() ->
......
......@@ -4,24 +4,37 @@ import edu.ntnu.idatt2105.dto.QuestionDTO;
import edu.ntnu.idatt2105.model.Question;
import edu.ntnu.idatt2105.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Controller class responsible for handling question-related endpoints.
*/
@RestController
@RequestMapping("/api/questions")
public class QuestionController {
private final QuestionService questionService;
/**
* Constructor for QuestionController.
*
* @param questionService An instance of QuestionService used for managing questions.
*/
@Autowired
public QuestionController(QuestionService questionService) {
this.questionService = questionService;
}
/**
* Endpoint for saving a question.
*
* @param questionDTO The question data to be saved.
* @return The saved question DTO.
*/
@PostMapping("/save")
public QuestionDTO saveQuestion(@RequestBody QuestionDTO questionDTO) {
Question question = questionService.createOrUpdateQuestion(questionDTO);
......@@ -38,6 +51,12 @@ public class QuestionController {
);
}
/**
* Endpoint for retrieving a question by ID.
*
* @param questionId The ID of the question to retrieve.
* @return The retrieved question DTO.
*/
@GetMapping("/get/{questionId}")
public QuestionDTO getQuestion(@PathVariable Integer questionId) {
Question question = questionService.findQuestionById(questionId);
......@@ -52,8 +71,35 @@ public class QuestionController {
);
}
/**
* Endpoint for deleting a question by ID.
*
* @param questionId The ID of the question to delete.
*/
@PostMapping("/delete/{questionId}")
public void deleteQuestion(@PathVariable Integer questionId) {
questionService.deleteQuestion(questionId);
}
/**
* Endpoint for retrieving all questions for a quiz.
*
* @param quizId The ID of the quiz.
* @return A list of question DTOs for the quiz.
*/
@GetMapping("/allQuestionsToAQuiz/{quizId}")
public List<QuestionDTO> getAllQuestionsToAQuiz(@PathVariable Integer quizId) {
List<Question> questions = questionService.findAllQuestionsToAQuiz(quizId);
return questions.stream()
.map(question -> new QuestionDTO(
question.getId(),
question.getQuestionText(),
question.getType(),
question.getAnswer(),
question.getOptionsList(),
question.getScore(),
question.getQuiz().getId()
))
.collect(Collectors.toList());
}
}
package edu.ntnu.idatt2105.controller;
import edu.ntnu.idatt2105.dto.QuizDTO;
import edu.ntnu.idatt2105.model.Question;
import edu.ntnu.idatt2105.model.Quiz;
import edu.ntnu.idatt2105.model.QuizCategory;
import edu.ntnu.idatt2105.model.QuizDifficulty;
import edu.ntnu.idatt2105.service.QuizService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
......@@ -16,23 +12,42 @@ import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Controller class for managing quizzes.
*/
@RestController
@RequestMapping("/api/quiz")
public class QuizController {
private final QuizService quizService;
/**
* Constructor for QuizController.
*
* @param quizService The service for handling quiz-related operations.
*/
@Autowired
public QuizController(QuizService quizService) {
this.quizService = quizService;
}
/**
* Endpoint for creating a new quiz.
*
* @param quizDTO The DTO containing information for creating the quiz.
* @return The created quiz DTO.
*/
@PostMapping("/create")
public QuizDTO createQuiz(@RequestBody QuizDTO quizDTO) {
return quizService.createQuiz(quizDTO);
}
/**
* Endpoint for updating an existing quiz.
*
* @param quizDTO The DTO containing information for updating the quiz.
* @return The updated quiz DTO.
*/
@PostMapping("/update")
public QuizDTO updateQuiz(@RequestBody QuizDTO quizDTO) {
if (quizDTO.getId() == null) {
......@@ -41,17 +56,32 @@ public class QuizController {
return quizService.updateQuiz(quizDTO);
}
/**
* Endpoint for deleting a quiz.
*
* @param payload The request payload containing the ID of the quiz to delete.
*/
@PostMapping("/delete")
public void deleteQuiz(@RequestBody Map<String, Integer> payload) {
quizService.deleteQuiz(payload.get("id"));
}
/**
* Endpoint for retrieving a quiz by its ID.
*
* @param quizId The ID of the quiz to retrieve.
* @return The quiz DTO.
*/
@GetMapping("/quiz/{quizId}")
public QuizDTO getQuizById(@PathVariable Integer quizId) {
return convertToDTO(quizService.findQuizById(quizId));
}
/**
* Endpoint for retrieving all quizzes.
*
* @return A list of quiz DTOs.
*/
@GetMapping("/")
public List<QuizDTO> getQuizzes() {
return quizService.findAllQuizzes().stream()
......@@ -59,6 +89,12 @@ public class QuizController {
.collect(Collectors.toList());
}
/**
* Endpoint for retrieving quizzes by category.
*
* @param category The category of quizzes to retrieve.
* @return A list of quiz DTOs.
*/
@GetMapping("/category")
public List<QuizDTO> getQuizzesByCategory(@RequestParam String category) {
return quizService.findAllQuizzesByCategory(QuizCategory.valueOf(category)).stream()
......@@ -66,6 +102,12 @@ public class QuizController {
.collect(Collectors.toList());
}
/**
* Endpoint for retrieving quizzes by difficulty.
*
* @param difficulty The difficulty of quizzes to retrieve.
* @return A list of quiz DTOs.
*/
@GetMapping("/difficulty")
public List<QuizDTO> getQuizzesByDifficulty(@RequestParam String difficulty) {
return quizService.findAllQuizzesByDifficulty(QuizDifficulty.valueOf(difficulty)).stream()
......@@ -73,6 +115,12 @@ public class QuizController {
.collect(Collectors.toList());
}
/**
* Endpoint for retrieving quizzes by creator ID.
*
* @param creatorId The ID of the creator of the quizzes to retrieve.
* @return A list of quiz DTOs.
*/
@GetMapping("/creator/{creatorId}")
public List<QuizDTO> getQuizzesByCreatorId(@PathVariable Integer creatorId) {
return quizService.findAllQuizzesByCreatorId(creatorId).stream()
......@@ -80,13 +128,19 @@ public class QuizController {
.collect(Collectors.toList());
}
public QuizDTO convertToDTO(Quiz quiz) {
/**
* Converts a Quiz entity to a QuizDTO.
*
* @param quiz The quiz entity to convert.
* @return The corresponding QuizDTO.
*/
private QuizDTO convertToDTO(Quiz quiz) {
QuizDTO quizDTO = new QuizDTO();
quizDTO.setId(quiz.getId());
quizDTO.setTitle(quiz.getTitle());
quizDTO.setCategory(quiz.getCategory());
quizDTO.setDifficulty(quiz.getDifficulty());
quizDTO.setCreatorId(quiz.getCreator().getId());
return quizDTO;
}
}
\ No newline at end of file
package edu.ntnu.idatt2105.controller;
import edu.ntnu.idatt2105.dto.QuizResultDTO;
import edu.ntnu.idatt2105.model.QuizResult;
import edu.ntnu.idatt2105.service.QuizResultService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
/**
* Controller class responsible for handling quiz result-related endpoints.
*/
@RestController
@RequestMapping("/api/results")
public class QuizResultController {
private final QuizResultService quizResultService;
/**
* Constructor for QuizResultController.
*
* @param quizResultService An instance of QuizResultService used for managing quiz results.
*/
@Autowired
public QuizResultController(QuizResultService quizResultService) {
this.quizResultService = quizResultService;
}
/**
* Endpoint for starting a new quiz result.
*
* @param quizResultDTO The data for starting the quiz result.
* @return The created quiz result DTO.
*/
@PostMapping("/create")
public QuizResultDTO startQuizResult(@RequestBody QuizResultDTO quizResultDTO) {
return convertToQuizResultDTO(quizResultService.startQuizResult(quizResultDTO));
}
/**
* Endpoint for completing a quiz.
*
* @param quizResultId The ID of the quiz result to complete.
* @return The completed quiz result DTO.
*/
@PostMapping("/complete/")
public QuizResultDTO completeQuiz(@RequestParam Integer quizResultId) {
return quizResultService.completeQuiz(quizResultId);
}
@GetMapping("/latest-result")
public QuizResultDTO getLatestQuizResultForUser(@RequestParam Integer userId) {
return quizResultService.findLatestQuizResultForUser(userId);
}
/**
* Endpoint for retrieving all quiz results for a user.
*
* @param userId The ID of the user.
* @return A list of quiz result DTOs for the user.
*/
@GetMapping("/results")
public List<QuizResultDTO> getQuizResultsForUser(@RequestParam("userId") Integer userId) {
List<QuizResult> quizResults = quizResultService.findAllResultsForUserId(userId);
......@@ -46,17 +64,21 @@ public class QuizResultController {
.collect(Collectors.toList());
}
/**
* Converts a QuizResult entity to a QuizResultDTO.
*
* @param quizResult The QuizResult entity to convert.
* @return The converted QuizResultDTO.
*/
public QuizResultDTO convertToQuizResultDTO(QuizResult quizResult) {
QuizResultDTO quizResultDTO = new QuizResultDTO();
quizResultDTO.setQuizId(quizResult.getQuiz().getId());
quizResultDTO.setUserId(quizResult.getUser().getId());
quizResultDTO.setTotalScore(quizResult.getScore());
quizResultDTO.setTotalScore(quizResult.getTotalScore());
quizResultDTO.setStatus(quizResult.getStatus());
quizResultDTO.setStartedAt(quizResult.getStartedAt());
quizResultDTO.setCompletedAt(quizResult.getCompletedAt());
return quizResultDTO;
}
}
package edu.ntnu.idatt2105.controller;
import edu.ntnu.idatt2105.dto.UserDTO;
import edu.ntnu.idatt2105.model.User;
import edu.ntnu.idatt2105.service.TokenService;
......@@ -9,7 +8,9 @@ import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* Controller class responsible for handling user-related endpoints.
*/
@RestController
@RequestMapping("/api/user")
public class UserController {
......@@ -17,19 +18,35 @@ public class UserController {
private final UserService userService;
private final TokenService tokenService;
/**
* Constructor for UserController.
*
* @param userService An instance of UserService used for managing users.
* @param tokenService An instance of TokenService used for token-related operations.
*/
public UserController(UserService userService, TokenService tokenService) {
this.tokenService = tokenService;
this.userService = userService;
}
/**
* Endpoint for retrieving all application users.
*
* @return A list of all application users.
*/
@GetMapping("/")
public List<User> getAppUsers() {
return userService.findAllAppUsers();
}
/**
* Endpoint for retrieving user ID from a token.
*
* @param token The token to extract user ID from.
* @return The user DTO associated with the token.
*/
@GetMapping("/getId/{token}")
public UserDTO getUserDTOFromToken(@PathVariable String token) {
public UserDTO getUserIdFromToken(@PathVariable String token) {
return tokenService.getUserDTOFromToken(token);
}
}
package edu.ntnu.idatt2105.dto;
import edu.ntnu.idatt2105.model.User;
/**
* DTO class representing the response after a successful login.
*/
public class LoginResponseDTO {
private String username;
private String password;
private String password; // Password should not be included in the response for security reasons.
private String jwt;
/**
* Default constructor for LoginResponseDTO.
*/
public LoginResponseDTO() {
super();
}
/**
* Constructor for LoginResponseDTO.
*
* @param user The user object.
* @param jwt The JWT token generated for the user.
*/
public LoginResponseDTO(User user, String jwt) {
this.username = user.getUsername();
this.password = user.getPassword();
this.jwt = jwt;
}
/**
* Get the username.
*
* @return The username.
*/
public String getUsername() {
return username;
}
/**
* Set the username.
*
* @param username The username.
*/
public void setUsername(String username) {
this.username = this.username;
}
/**
* Get the password.
*
* @return The password. Note: Password should not be included in the response for security reasons.
*/
public String getPassword() {
return password;
}
/**
* Set the password.
*
* @param password The password.
*/
public void setPassword(String password) {
this.password = password;
}
/**
* Get the JWT token.
*
* @return The JWT token.
*/
public String getJwt() {
return jwt;
}
/**
* Set the JWT token.
*
* @param jwt The JWT token.
*/
public void setJwt(String jwt) {
this.jwt = jwt;
}
......@@ -47,7 +88,7 @@ public class LoginResponseDTO {
public String toString() {
return "LoginResponseDTO{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
", password='" + password + '\'' + // Password should not be included in the response for security reasons.
", jwt='" + jwt + '\'' +
'}';
}
......
package edu.ntnu.idatt2105.dto;
/**
* DTO class representing a question-answer pair.
*/
public class QuestionAnswerDTO {
private Integer id;
private Integer questionId;
private Integer quizResultId;
private String givenAnswer;
private boolean correct;
/**
* Default constructor for QuestionAnswerDTO.
*/
public QuestionAnswerDTO() {
}
/**
* Constructor for QuestionAnswerDTO.
*
* @param id The ID of the question-answer pair.
* @param questionId The ID of the question.
* @param givenAnswer The answer provided by the user.
* @param correct Whether the answer is correct or not.
*/
public QuestionAnswerDTO(Integer id, Integer questionId, String givenAnswer, boolean correct) {
this.id = id;
this.questionId = questionId;
......@@ -16,34 +31,74 @@ public class QuestionAnswerDTO {
this.correct = correct;
}
/**
* Get the ID of the question-answer pair.
*
* @return The ID.
*/
public Integer getId() {
return id;
}
/**
* Set the ID of the question-answer pair.
*
* @param id The ID to set.
*/
public void setId(Integer id) {
this.id = id;
}
/**
* Get the ID of the question.
*
* @return The question ID.
*/
public Integer getQuestionId() {
return questionId;
}
/**
* Set the ID of the question.
*
* @param questionId The question ID to set.
*/
public void setQuestionId(Integer questionId) {
this.questionId = questionId;
}
/**
* Get the answer provided by the user.
*
* @return The given answer.
*/
public String getGivenAnswer() {
return givenAnswer;
}
/**
* Set the answer provided by the user.
*
* @param givenAnswer The given answer to set.
*/
public void setGivenAnswer(String givenAnswer) {
this.givenAnswer = givenAnswer;
}
/**
* Check if the answer is correct.
*
* @return True if the answer is correct, false otherwise.
*/
public boolean isCorrect() {
return correct;
}
/**
* Set whether the answer is correct or not.
*
* @param correct True if the answer is correct, false otherwise.
*/
public void setCorrect(boolean correct) {
this.correct = correct;
}
......
package edu.ntnu.idatt2105.dto;
import edu.ntnu.idatt2105.model.QuestionType;
import jakarta.annotation.Nullable;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* DTO class representing a question.
*/
public class QuestionDTO {
private Integer id;
private Integer quizId;
private String questionText;
private QuestionType type;
private String answer;
@Nullable
private List<String> options;
private int score;
/**
* Default constructor for QuestionDTO.
*/
public QuestionDTO() {
}
/**
* Constructor for QuestionDTO.
*
* @param id The ID of the question.
* @param questionText The text of the question.
* @param type The type of the question.
* @param answer The correct answer to the question.
* @param options The list of options for the question (if applicable).
* @param score The score assigned to the question.
* @param quizId The ID of the quiz the question belongs to.
*/
public QuestionDTO(Integer id, String questionText, QuestionType type, String answer, List<String> options, int score, Integer quizId) {
this.id = id;
this.questionText = questionText;
......@@ -29,63 +47,137 @@ public class QuestionDTO {
this.quizId = quizId;
}
// Getters og setters
/**
* Get the ID of the question.
*
* @return The ID of the question.
*/
public Integer getId() {
return id;
}
/**
* Set the ID of the question.
*
* @param id The ID to set.
*/
public void setId(Integer id) {
this.id = id;
}
/**
* Get the text of the question.
*
* @return The text of the question.
*/
public String getQuestionText() {
return questionText;
}
/**
* Set the text of the question.
*
* @param questionText The text to set.
*/
public void setQuestionText(String questionText) {
this.questionText = questionText;
}
/**
* Get the type of the question.
*
* @return The type of the question.
*/
public QuestionType getType() {
return type;
}
/**
* Set the type of the question.
*
* @param type The type to set.
*/
public void setType(QuestionType type) {
this.type = type;
}
/**
* Get the correct answer to the question.
*
* @return The correct answer to the question.
*/
public String getAnswer() {
return answer;
}
/**
* Set the correct answer to the question.
*
* @param answer The answer to set.
*/
public void setAnswer(String answer) {
this.answer = answer;
}
/**
* Get the list of options for the question.
*
* @return The list of options for the question.
*/
public List<String> getOptions() {
return options;
}
/**
* Set the list of options for the question.
*
* @param options The list of options to set.
*/
public void setOptions(List<String> options) {
this.options = options;
}
/**
* Get the score assigned to the question.
*
* @return The score assigned to the question.
*/
public int getScore() {
return score;
}
/**
* Set the score assigned to the question.
*
* @param score The score to set.
*/
public void setScore(int score) {
this.score = score;
}
/**
* Get the ID of the quiz the question belongs to.
*
* @return The ID of the quiz.
*/
public Integer getQuizId() {
return quizId;
}
/**
* Set the ID of the quiz the question belongs to.
*
* @param quizId The ID of the quiz to set.
*/
public void setQuizId(Integer quizId) {
this.quizId = quizId;
}
/**
* Sets the options from a string containing options separated by '*' character.
*
* @param optionsString The string containing options.
*/
public void setOptionsFromString(String optionsString) {
if (optionsString != null && !optionsString.isEmpty()) {
this.options = Arrays.stream(optionsString.split("\\*"))
......@@ -93,6 +185,12 @@ public class QuestionDTO {
}
}
/**
* Gets the options as a string with options separated by '*' character.
*
* @return The options as a string.
*/
@Nullable
public String getOptionsAsString() {
return String.join("*", this.options);
}
......
package edu.ntnu.idatt2105.dto;
import edu.ntnu.idatt2105.model.QuizCategory;
import edu.ntnu.idatt2105.model.QuizDifficulty;
import java.util.List;
/**
* DTO class representing a quiz.
*/
public class QuizDTO {
private Integer id;
private String title;
......@@ -13,9 +13,20 @@ public class QuizDTO {
private QuizCategory category;
private QuizDifficulty difficulty;
/**
* Default constructor for QuizDTO.
*/
public QuizDTO() {
}
/**
* Constructor for QuizDTO.
*
* @param title The title of the quiz.
* @param creatorId The ID of the creator of the quiz.
* @param category The category of the quiz.
* @param difficulty The difficulty of the quiz.
*/
public QuizDTO(String title, Integer creatorId, QuizCategory category, QuizDifficulty difficulty) {
this.title = title;
this.creatorId = creatorId;
......@@ -23,43 +34,92 @@ public class QuizDTO {
this.difficulty = difficulty;
}
// Getters and setters
/**
* Get the ID of the quiz.
*
* @return The ID of the quiz.
*/
public Integer getId() {
return id;
}
/**
* Set the ID of the quiz.
*
* @param id The ID to set.
*/
public void setId(Integer id) {
this.id = id;
}
/**
* Get the title of the quiz.
*
* @return The title of the quiz.
*/
public String getTitle() {
return title;
}
/**
* Set the title of the quiz.
*
* @param title The title to set.
*/
public void setTitle(String title) {
this.title = title;
}
/**
* Get the ID of the creator of the quiz.
*
* @return The ID of the creator of the quiz.
*/
public Integer getCreatorId() {
return creatorId;
}
/**
* Set the ID of the creator of the quiz.
*
* @param creatorId The ID of the creator to set.
*/
public void setCreatorId(Integer creatorId) {
this.creatorId = creatorId;
}
/**
* Get the category of the quiz.
*
* @return The category of the quiz.
*/
public QuizCategory getCategory() {
return category;
}
/**
* Set the category of the quiz.
*
* @param category The category to set.
*/
public void setCategory(QuizCategory category) {
this.category = category;
}
/**
* Get the difficulty of the quiz.
*
* @return The difficulty of the quiz.
*/
public QuizDifficulty getDifficulty() {
return difficulty;
}
/**
* Set the difficulty of the quiz.
*
* @param difficulty The difficulty to set.
*/
public void setDifficulty(QuizDifficulty difficulty) {
this.difficulty = difficulty;
}
......
package edu.ntnu.idatt2105.dto;
import java.time.LocalDateTime;
import java.util.List;
/**
* DTO class representing a quiz result.
*/
public class QuizResultDTO {
private Integer id;
private Integer quizId;
private Integer userId;
private List<QuestionAnswerDTO> answers;
private int totalScore;
private String status;
private LocalDateTime startedAt;
private LocalDateTime completedAt;
/**
* Default constructor for QuizResultDTO.
*/
public QuizResultDTO() {
}
public QuizResultDTO(Integer id, Integer quizId, Integer userId, List<QuestionAnswerDTO> answers, int totalScore, String status, LocalDateTime startedAt, LocalDateTime completedAt) {
/**
* Constructor for QuizResultDTO.
*
* @param id The ID of the quiz result.
* @param quizId The ID of the quiz.
* @param userId The ID of the user who took the quiz.
* @param totalScore The total score achieved in the quiz.
* @param status The status of the quiz result.
* @param startedAt The time when the quiz was started.
* @param completedAt The time when the quiz was completed.
*/
public QuizResultDTO(Integer id, Integer quizId, Integer userId, int totalScore, String status, LocalDateTime startedAt, LocalDateTime completedAt) {
this.id = id;
this.quizId = quizId;
this.userId = userId;
this.answers = answers;
this.totalScore = totalScore;
this.status = status;
this.startedAt = startedAt;
this.completedAt = completedAt;
}
/**
* Get the ID of the quiz result.
*
* @return The ID of the quiz result.
*/
public Integer getId() {
return id;
}
/**
* Set the ID of the quiz result.
*
* @param id The ID to set.
*/
public void setId(Integer id) {
this.id = id;
}
/**
* Get the ID of the quiz.
*
* @return The ID of the quiz.
*/
public Integer getQuizId() {
return quizId;
}
/**
* Set the ID of the quiz.
*
* @param quizId The ID of the quiz to set.
*/
public void setQuizId(Integer quizId) {
this.quizId = quizId;
}
/**
* Get the ID of the user who took the quiz.
*
* @return The ID of the user.
*/
public Integer getUserId() {
return userId;
}
/**
* Set the ID of the user who took the quiz.
*
* @param userId The ID of the user to set.
*/
public void setUserId(Integer userId) {
this.userId = userId;
}
public List<QuestionAnswerDTO> getAnswers() {
return answers;
}
public void setAnswers(List<QuestionAnswerDTO> answers) {
this.answers = answers;
}
/**
* Get the total score achieved in the quiz.
*
* @return The total score achieved.
*/
public int getTotalScore() {
return totalScore;
}
/**
* Set the total score achieved in the quiz.
*
* @param totalScore The total score to set.
*/
public void setTotalScore(int totalScore) {
this.totalScore = totalScore;
}
/**
* Get the status of the quiz result.
*
* @return The status of the quiz result.
*/
public String getStatus() {
return status;
}
/**
* Set the status of the quiz result.
*
* @param status The status to set.
*/
public void setStatus(String status) {
this.status = status;
}
/**
* Get the time when the quiz was started.
*
* @return The time when the quiz was started.
*/
public LocalDateTime getStartedAt() {
return startedAt;
}
/**
* Set the time when the quiz was started.
*
* @param startedAt The time when the quiz was started.
*/
public void setStartedAt(LocalDateTime startedAt) {
this.startedAt = startedAt;
}
/**
* Get the time when the quiz was completed.
*
* @return The time when the quiz was completed.
*/
public LocalDateTime getCompletedAt() {
return completedAt;
}
/**
* Set the time when the quiz was completed.
*
* @param completedAt The time when the quiz was completed.
*/
public void setCompletedAt(LocalDateTime completedAt) {
this.completedAt = completedAt;
}
......@@ -98,7 +173,6 @@ public class QuizResultDTO {
"id=" + id +
", quizId=" + quizId +
", userId=" + userId +
", answers=" + answers +
", score=" + totalScore +
'}';
}
......
package edu.ntnu.idatt2105.dto;
/**
* DTO class representing a token.
*/
public class TokenDTO {
private String token;
/**
* Default constructor for TokenDTO.
*/
public TokenDTO() {
super();
}
/**
* Constructor for TokenDTO.
*
* @param token The token string.
*/
public TokenDTO(String token) {
super();
this.token = token;
}
/**
* Get the token string.
*
* @return The token string.
*/
public String getToken() {
return token;
}
/**
* Set the token string.
*
* @param token The token string to set.
*/
public void setToken(String token) {
this.token = token;
}
......
package edu.ntnu.idatt2105.dto;
import java.util.List;
/**
* DTO class representing a user.
*/
public class UserDTO extends UserRegistrationDTO {
private Integer id;
// Assuming you might need more fields here, such as role, etc.
/**
* Default constructor for UserDTO.
*/
public UserDTO() {
super();
}
/**
* Constructor for UserDTO.
*
* @param id The ID of the user.
* @param username The username of the user.
* @param password The password of the user.
*/
public UserDTO(Integer id, String username, String password) {
super(username, password);
this.id = id;
}
// Getters and setters for the 'id' field
/**
* Get the ID of the user.
*
* @return The ID of the user.
*/
public Integer getId() {
return id;
}
/**
* Set the ID of the user.
*
* @param id The ID to set.
*/
public void setId(Integer id) {
this.id = id;
}
......
package edu.ntnu.idatt2105.dto;
/**
* DTO class representing user registration information.
*/
public class UserRegistrationDTO {
private String username;
private String password;
/**
* Default constructor for UserRegistrationDTO.
*/
public UserRegistrationDTO() {
super();
}
/**
* Constructor for UserRegistrationDTO.
*
* @param username The username for registration.
* @param password The password for registration.
*/
public UserRegistrationDTO(String username, String password) {
this.username = username;
this.password = password;
}
// Getters and setters
/**
* Get the username for registration.
*
* @return The username for registration.
*/
public String getUsername() {
return username;
}
/**
* Set the username for registration.
*
* @param username The username to set.
*/
public void setUsername(String username) {
this.username = username;
}
/**
* Get the password for registration.
*
* @return The password for registration.
*/
public String getPassword() {
return password;
}
/**
* Set the password for registration.
*
* @param password The password to set.
*/
public void setPassword(String password) {
this.password = password;
}
......
package edu.ntnu.idatt2105.exception;
/**
* Exception indicating that a question was not found.
*/
public class QuestionNotFoundException extends RuntimeException {
/**
* Constructor for QuestionNotFoundException.
*
* @param message The exception message.
*/
public QuestionNotFoundException(String message) {
super(message);
}
......
package edu.ntnu.idatt2105.exception;
/**
* Exception indicating that a quiz was not found.
*/
public class QuizNotFoundException extends RuntimeException {
/**
* Constructor for QuizNotFoundException.
*
* @param message The exception message.
*/
public QuizNotFoundException(String message) {
super(message);
}
......
package edu.ntnu.idatt2105.exception;
/**
* Exception indicating that a user was not found.
*/
public class UserNotFoundException extends RuntimeException {
/**
* Constructor for UserNotFoundException.
*
* @param message The exception message.
*/
public UserNotFoundException(String message) {
super(message);
}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment