diff --git a/src/main/java/com/uniovi/components/generators/QuestionGeneratorV2.java b/src/main/java/com/uniovi/components/generators/QuestionGeneratorV2.java index 7decf49b..db4afcb4 100644 --- a/src/main/java/com/uniovi/components/generators/QuestionGeneratorV2.java +++ b/src/main/java/com/uniovi/components/generators/QuestionGeneratorV2.java @@ -2,12 +2,11 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import com.uniovi.dto.AnswerDto; -import com.uniovi.dto.CategoryDto; -import com.uniovi.dto.QuestionDto; import com.uniovi.entities.Answer; import com.uniovi.entities.Category; import com.uniovi.entities.Question; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.URI; @@ -22,20 +21,20 @@ import java.util.Random; public class QuestionGeneratorV2 implements QuestionGenerator{ - - private JsonNode jsonNode; - private String language_placeholder; - private String question_placeholder; - private String answer_placeholder; + private final JsonNode jsonNode; + private final String languagePlaceholder; + private final String questionPlaceholder; + private final String answerPlaceholder; private String language; - private Random random = new SecureRandom(); + private final Random random = new SecureRandom(); + private Logger logger = LoggerFactory.getLogger(QuestionGeneratorV2.class); public QuestionGeneratorV2(JsonNode jsonNode) { this.jsonNode = jsonNode; - this.language_placeholder = jsonNode.get("language_placeholder").textValue(); - this.question_placeholder = jsonNode.get("question_placeholder").textValue(); - this.answer_placeholder = jsonNode.get("answer_placeholder").textValue(); + this.languagePlaceholder = jsonNode.get("language_placeholder").textValue(); + this.questionPlaceholder = jsonNode.get("question_placeholder").textValue(); + this.answerPlaceholder = jsonNode.get("answer_placeholder").textValue(); } @Override @@ -69,9 +68,9 @@ private List generateQuestion(JsonNode question, Category cat) throws String answerLabel= question.get("answer").textValue(); // Replace the placeholders in the query with the actual values - query = query.replace(language_placeholder, language). - replace(question_placeholder, questionLabel). - replace(answer_placeholder, answerLabel); + query = query.replace(languagePlaceholder, language). + replace(questionPlaceholder, questionLabel). + replace(answerPlaceholder, answerLabel); // Execute the query and get the results JsonNode results = getQueryResult(query); @@ -91,7 +90,7 @@ private List generateQuestion(JsonNode question, Category cat) throws if (statement != null) { // Generate the question statement - String questionStatement = statement.replace(question_placeholder, result.path(questionLabel).path("value").asText()); + String questionStatement = statement.replace(questionPlaceholder, result.path(questionLabel).path("value").asText()); // Generate the question Question q = new Question(questionStatement, options, correct, cat, language); @@ -110,8 +109,8 @@ private List generateOptions(JsonNode results, String correctAnswer, Str int tries = 0; while (options.size() < 3 && tries < 10) { - int random = (int) (this.random.nextFloat() * size); - String option = results.get(random).path(answerLabel).path("value").asText(); + int randomIdx = random.nextInt(size); + String option = results.get(randomIdx).path(answerLabel).path("value").asText(); if (!option.equals(correctAnswer) && !usedOptions.contains(option) ) { usedOptions.add(option); options.add(new Answer(option, false)); @@ -138,7 +137,7 @@ private String prepareStatement(JsonNode question) { private JsonNode getQueryResult(String query) throws IOException, InterruptedException { - System.out.println("Query: " + query); + logger.info("Query: {}", query); HttpClient client = HttpClient.newHttpClient(); JsonNode resultsNode; String endpointUrl = "https://query.wikidata.org/sparql?query=" + diff --git a/src/main/java/com/uniovi/configuration/SecurityConfig.java b/src/main/java/com/uniovi/configuration/SecurityConfig.java index 068364b0..6f1c0087 100644 --- a/src/main/java/com/uniovi/configuration/SecurityConfig.java +++ b/src/main/java/com/uniovi/configuration/SecurityConfig.java @@ -40,7 +40,7 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .csrf(csrf -> csrf .ignoringRequestMatchers("/api/**") ) - .authorizeHttpRequests((authorize) -> + .authorizeHttpRequests(authorize -> authorize .requestMatchers("/css/**", "/img/**", "/script/**").permitAll() .requestMatchers("/home/**").authenticated() diff --git a/src/main/java/com/uniovi/controllers/CustomErrorController.java b/src/main/java/com/uniovi/controllers/CustomErrorController.java index 1c3c2ae8..074291ca 100644 --- a/src/main/java/com/uniovi/controllers/CustomErrorController.java +++ b/src/main/java/com/uniovi/controllers/CustomErrorController.java @@ -15,6 +15,7 @@ @Controller public class CustomErrorController extends BasicErrorController { + private static final String PATH = "error"; @Autowired public CustomErrorController(ErrorAttributes errorAttributes, ServerProperties serverProperties, List errorViewResolvers) { super(errorAttributes, serverProperties.getError(), errorViewResolvers); @@ -23,10 +24,10 @@ public CustomErrorController(ErrorAttributes errorAttributes, ServerProperties s @RequestMapping(value = "/error") public String error(Model model, HttpServletRequest webRequest) { Map errorAttributes = this.getErrorAttributes(webRequest, ErrorAttributeOptions.defaults()); - model.addAttribute("error", errorAttributes.get("error")); + model.addAttribute(PATH, errorAttributes.get(PATH)); model.addAttribute("message", errorAttributes.get("message")); model.addAttribute("status", errorAttributes.get("status")); model.addAttribute("trace", errorAttributes.get("trace")); // Add the stack trace - return "error"; + return PATH; } } diff --git a/src/main/java/com/uniovi/controllers/GameController.java b/src/main/java/com/uniovi/controllers/GameController.java index f8c0ffa3..5154df38 100644 --- a/src/main/java/com/uniovi/controllers/GameController.java +++ b/src/main/java/com/uniovi/controllers/GameController.java @@ -20,6 +20,8 @@ @Controller public class GameController { + private static final String GAMESESSION_STR = "gameSession"; + private final QuestionService questionService; private final GameSessionService gameSessionService; private final PlayerService playerService; @@ -31,7 +33,6 @@ public GameController(QuestionService questionService, GameSessionService gameSe this.playerService = playerService; } - /** * This method is used to get the game view and to start the game * @param model The model to be used @@ -39,14 +40,14 @@ public GameController(QuestionService questionService, GameSessionService gameSe */ @GetMapping("/game") public String getGame(HttpSession session, Model model, Principal principal) { - GameSession gameSession = (GameSession) session.getAttribute("gameSession"); + GameSession gameSession = (GameSession) session.getAttribute(GAMESESSION_STR); if (gameSession != null) { if (checkUpdateGameSession(gameSession, session)) { return "game/fragments/gameFinished"; } } else { gameSession = gameSessionService.startNewGame(getLoggedInPlayer(principal)); - session.setAttribute("gameSession", gameSession); + session.setAttribute(GAMESESSION_STR, gameSession); } model.addAttribute("question", gameSession.getCurrentQuestion()); @@ -66,14 +67,14 @@ public String getGame(HttpSession session, Model model, Principal principal) { */ @GetMapping("/game/{idQuestion}/{idAnswer}") public String getCheckResult(@PathVariable Long idQuestion, @PathVariable Long idAnswer, Model model, HttpSession session) { - GameSession gameSession = (GameSession) session.getAttribute("gameSession"); + GameSession gameSession = (GameSession) session.getAttribute(GAMESESSION_STR); if (gameSession == null) { return "redirect:/game"; } if (!gameSession.hasQuestionId(idQuestion)) { model.addAttribute("score", gameSession.getScore()); - session.removeAttribute("gameSession"); + session.removeAttribute(GAMESESSION_STR); return "redirect:/game"; // if someone wants to exploit the game, just redirect to the game page } @@ -101,11 +102,11 @@ else if(questionService.checkAnswer(idQuestion, idAnswer)) { @GetMapping("/game/update") public String updateGame(Model model, HttpSession session) { - GameSession gameSession = (GameSession) session.getAttribute("gameSession"); + GameSession gameSession = (GameSession) session.getAttribute(GAMESESSION_STR); Question nextQuestion = gameSession.getCurrentQuestion(); if (nextQuestion == null) { gameSessionService.endGame(gameSession); - session.removeAttribute("gameSession"); + session.removeAttribute(GAMESESSION_STR); model.addAttribute("score", gameSession.getScore()); return "game/fragments/gameFinished"; } @@ -122,10 +123,10 @@ public String updateGame(Model model, HttpSession session) { @GetMapping("/game/finished/{points}") public String finishGame(@PathVariable int points, Model model, HttpSession session) { - GameSession gameSession = (GameSession) session.getAttribute("gameSession"); + GameSession gameSession = (GameSession) session.getAttribute(GAMESESSION_STR); if (gameSession != null) { gameSessionService.endGame(gameSession); - session.removeAttribute("gameSession"); + session.removeAttribute(GAMESESSION_STR); } model.addAttribute("score", points); return "game/gameFinished"; @@ -134,7 +135,7 @@ public String finishGame(@PathVariable int points, Model model, HttpSession sess @GetMapping("/game/points") @ResponseBody public String getPoints(HttpSession session) { - GameSession gameSession = (GameSession) session.getAttribute("gameSession"); + GameSession gameSession = (GameSession) session.getAttribute(GAMESESSION_STR); if (gameSession != null) return String.valueOf(gameSession.getScore()); else @@ -144,7 +145,7 @@ public String getPoints(HttpSession session) { @GetMapping("/game/currentQuestion") @ResponseBody public String getCurrentQuestion(HttpSession session) { - GameSession gameSession = (GameSession) session.getAttribute("gameSession"); + GameSession gameSession = (GameSession) session.getAttribute(GAMESESSION_STR); if (gameSession != null) return String.valueOf(gameSession.getAnsweredQuestions().size()+1); else @@ -171,7 +172,7 @@ private boolean checkUpdateGameSession(GameSession gameSession, HttpSession sess gameSession.addAnsweredQuestion(gameSession.getCurrentQuestion()); if (gameSession.getQuestionsToAnswer().isEmpty()) { gameSessionService.endGame(gameSession); - session.removeAttribute("gameSession"); + session.removeAttribute(GAMESESSION_STR); return true; } } diff --git a/src/main/java/com/uniovi/controllers/HomeController.java b/src/main/java/com/uniovi/controllers/HomeController.java index a89f0f31..8fbd9cf7 100644 --- a/src/main/java/com/uniovi/controllers/HomeController.java +++ b/src/main/java/com/uniovi/controllers/HomeController.java @@ -9,6 +9,8 @@ import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; +import java.util.Optional; + @Controller public class HomeController{ private final PlayerService playerService; @@ -27,16 +29,21 @@ public String home(){ @GetMapping("/home/apikey") public String apiKeyHome(Authentication auth, Model model) { - Player player = playerService.getUserByUsername(auth.getName()).get(); - model.addAttribute("apiKey", player.getApiKey()); + Optional playerOpt = playerService.getUserByUsername(auth.getName()); + if (playerOpt.isPresent()) { + Player player = playerOpt.get(); + model.addAttribute("apiKey", player.getApiKey()); + } return "player/apiKeyHome"; } @GetMapping("/home/apikey/create") public String createApiKey(Authentication auth) { - Player player = playerService.getUserByUsername(auth.getName()).get(); - if (player.getApiKey() == null) { - apiKeyService.createApiKey(player); + if (playerService.getUserByUsername(auth.getName()).isPresent()) { + Player player = playerService.getUserByUsername(auth.getName()).get(); + if (player.getApiKey() == null) { + apiKeyService.createApiKey(player); + } } return "redirect:/home/apikey"; } diff --git a/src/main/java/com/uniovi/controllers/PlayersController.java b/src/main/java/com/uniovi/controllers/PlayersController.java index 0df52d19..20cae551 100644 --- a/src/main/java/com/uniovi/controllers/PlayersController.java +++ b/src/main/java/com/uniovi/controllers/PlayersController.java @@ -20,7 +20,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; -import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; @@ -94,7 +93,6 @@ public String showLoginForm(Model model, @RequestParam(value = "error", required HttpSession session) { if (error != null) { model.addAttribute("error", session.getAttribute("loginErrorMessage")); - System.out.println(session.getAttribute("loginErrorMessage")); } if (SecurityConfig.isAuthenticated()) @@ -247,7 +245,7 @@ public String changeRoles(HttpServletResponse response, @RequestParam String use @GetMapping("/player/admin/questionManagement") public String showQuestionManagementFragment(Model model) throws IOException { - File jsonFile = new File(QuestionGeneratorService.jsonFilePath); + File jsonFile = new File(QuestionGeneratorService.JSON_FILE_PATH); ObjectMapper objectMapper = new ObjectMapper(); JsonNode json = objectMapper.readTree(jsonFile); model.addAttribute("jsonContent", json.toString()); @@ -257,7 +255,7 @@ public String showQuestionManagementFragment(Model model) throws IOException { @GetMapping("/player/admin/deleteAllQuestions") @ResponseBody - public String deleteAllQuestions() { + public String deleteAllQuestions() throws IOException { questionService.deleteAllQuestions(); return "Questions deleted"; } @@ -273,7 +271,7 @@ public String saveQuestions(HttpServletResponse response, @RequestParam String j printer.indentArraysWith(indenter); // Indent JSON arrays ObjectMapper mapper = new ObjectMapper(); - mapper.writer(printer).writeValue(new FileOutputStream(QuestionGeneratorService.jsonFilePath), node); + mapper.writer(printer).writeValue(new FileOutputStream(QuestionGeneratorService.JSON_FILE_PATH), node); return "Questions saved"; } catch (Exception e) { diff --git a/src/main/java/com/uniovi/controllers/api/PlayerApiController.java b/src/main/java/com/uniovi/controllers/api/PlayerApiController.java index 677cac9e..74641915 100644 --- a/src/main/java/com/uniovi/controllers/api/PlayerApiController.java +++ b/src/main/java/com/uniovi/controllers/api/PlayerApiController.java @@ -30,7 +30,6 @@ import org.springframework.validation.SimpleErrors; import org.springframework.web.bind.annotation.*; -import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; diff --git a/src/main/java/com/uniovi/controllers/api/QuestionsApiController.java b/src/main/java/com/uniovi/controllers/api/QuestionsApiController.java index cdff40cf..68b3b5a7 100644 --- a/src/main/java/com/uniovi/controllers/api/QuestionsApiController.java +++ b/src/main/java/com/uniovi/controllers/api/QuestionsApiController.java @@ -160,7 +160,7 @@ public String addQuestion(HttpServletResponse response, @RequestHeader("API-KEY" return objectMapper.writeValueAsString(error); } - if (questionDto.getOptions().stream().anyMatch(option -> option.isCorrect())) { + if (questionDto.getOptions().stream().anyMatch(AnswerDto::isCorrect)) { questionDto.setCorrectAnswer(questionDto.getOptions().stream().filter(option -> option.isCorrect()).findFirst().get()); } diff --git a/src/main/java/com/uniovi/entities/Associations.java b/src/main/java/com/uniovi/entities/Associations.java index bb35ebd0..efa34f78 100644 --- a/src/main/java/com/uniovi/entities/Associations.java +++ b/src/main/java/com/uniovi/entities/Associations.java @@ -3,7 +3,11 @@ import java.util.*; public class Associations { + private static final String UTILITY_CLASS = "Utility class"; + private Associations() { throw new IllegalStateException(UTILITY_CLASS); } + public static class PlayerRole { + private PlayerRole() { throw new IllegalStateException(UTILITY_CLASS); } /** * Add a new association between a player and a role * @@ -28,6 +32,7 @@ public static void removeRole(Player player, Role role) { } public static class PlayerApiKey { + private PlayerApiKey() { throw new IllegalStateException(UTILITY_CLASS); } /** * Add a new association between a player and an API key * @@ -52,6 +57,7 @@ public static void removeApiKey(Player player, ApiKey apiKey) { } public static class ApiKeyAccessLog { + private ApiKeyAccessLog() { throw new IllegalStateException(UTILITY_CLASS); } /** * Add a new association between an API key and an access log * @@ -76,6 +82,7 @@ public static void removeAccessLog(ApiKey apiKey, RestApiAccessLog accessLog) { } public static class PlayerGameSession { + private PlayerGameSession() { throw new IllegalStateException(UTILITY_CLASS); } /** * Add a new association between a player and a game session * @@ -101,6 +108,7 @@ public static void removeGameSession(Player player, GameSession gameSession) { } public static class QuestionAnswers { + private QuestionAnswers() { throw new IllegalStateException(UTILITY_CLASS); } /** * Add a new association between a question and an answer * @@ -130,15 +138,10 @@ public static void removeAnswer(Question question, List answer) { } question.setCorrectAnswer(null); } - //public static void removeAnswer(Question question, List answer) { - // question.getOptions().remove(answer); - //for (Answer a : answer) { - // a.setQuestion(null); - //} - //} } public static class QuestionsCategory { + private QuestionsCategory() { throw new IllegalStateException(UTILITY_CLASS); } /** * Add a new association between a question and a category * diff --git a/src/main/java/com/uniovi/entities/GameSession.java b/src/main/java/com/uniovi/entities/GameSession.java index a4285788..a18b17a4 100644 --- a/src/main/java/com/uniovi/entities/GameSession.java +++ b/src/main/java/com/uniovi/entities/GameSession.java @@ -4,7 +4,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.uniovi.interfaces.JsonEntity; import jakarta.persistence.*; -import jakarta.validation.constraints.NotEmpty; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; diff --git a/src/main/java/com/uniovi/entities/Question.java b/src/main/java/com/uniovi/entities/Question.java index aad73c71..7704ef82 100644 --- a/src/main/java/com/uniovi/entities/Question.java +++ b/src/main/java/com/uniovi/entities/Question.java @@ -78,10 +78,6 @@ public boolean isCorrectAnswer(Answer answer){ return answer.isCorrect(); } - /*public void scrambleOptions(){ - Collections.shuffle(options); USO EN LOS TESTS Y ABSTRACTQUESTIONGENERATOR - }*/ - public List returnScrambledOptions(){ Collections.shuffle(options); return options; diff --git a/src/main/java/com/uniovi/repositories/QuestionRepository.java b/src/main/java/com/uniovi/repositories/QuestionRepository.java index e7dfa216..407f233b 100644 --- a/src/main/java/com/uniovi/repositories/QuestionRepository.java +++ b/src/main/java/com/uniovi/repositories/QuestionRepository.java @@ -7,7 +7,6 @@ import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; -import java.util.Optional; import java.util.List; public interface QuestionRepository extends CrudRepository { Question findByStatement(String statement); diff --git a/src/main/java/com/uniovi/services/AnswerService.java b/src/main/java/com/uniovi/services/AnswerService.java index ff2ddd44..015aebc2 100644 --- a/src/main/java/com/uniovi/services/AnswerService.java +++ b/src/main/java/com/uniovi/services/AnswerService.java @@ -1,7 +1,6 @@ package com.uniovi.services; import com.uniovi.entities.Answer; -import com.uniovi.entities.Category; import com.uniovi.entities.Question; import org.springframework.stereotype.Service; diff --git a/src/main/java/com/uniovi/services/CategoryService.java b/src/main/java/com/uniovi/services/CategoryService.java index 52f29eb7..9df8c82b 100644 --- a/src/main/java/com/uniovi/services/CategoryService.java +++ b/src/main/java/com/uniovi/services/CategoryService.java @@ -1,7 +1,6 @@ package com.uniovi.services; import com.uniovi.entities.Category; -import com.uniovi.entities.Question; import org.springframework.stereotype.Service; import java.util.List; diff --git a/src/main/java/com/uniovi/services/CustomUserDetailsService.java b/src/main/java/com/uniovi/services/CustomUserDetailsService.java index 2a1535ad..189ca630 100644 --- a/src/main/java/com/uniovi/services/CustomUserDetailsService.java +++ b/src/main/java/com/uniovi/services/CustomUserDetailsService.java @@ -11,7 +11,6 @@ import org.springframework.stereotype.Service; import java.util.Collection; -import java.util.stream.Collectors; @Service("userDetailsService") public class CustomUserDetailsService implements UserDetailsService { @@ -36,9 +35,8 @@ public UserDetails loadUserByUsername(String username) throws UsernameNotFoundEx } private Collection< ? extends GrantedAuthority> mapRolesToAuthorities(Collection roles) { - Collection < ? extends GrantedAuthority> mapRoles = roles.stream() + return roles.stream() .map(role -> new SimpleGrantedAuthority(role.getName())) - .collect(Collectors.toList()); - return mapRoles; + .toList(); } } diff --git a/src/main/java/com/uniovi/services/GameSessionService.java b/src/main/java/com/uniovi/services/GameSessionService.java index e3eb4c55..f1872836 100644 --- a/src/main/java/com/uniovi/services/GameSessionService.java +++ b/src/main/java/com/uniovi/services/GameSessionService.java @@ -2,12 +2,9 @@ import com.uniovi.entities.GameSession; import com.uniovi.entities.Player; -import com.uniovi.services.impl.GameSessionImpl; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; -import org.springframework.stereotype.Service; -import java.util.HashMap; import java.util.List; public interface GameSessionService { diff --git a/src/main/java/com/uniovi/services/InsertSampleDataService.java b/src/main/java/com/uniovi/services/InsertSampleDataService.java index 0b2b1b83..2a00d6b3 100644 --- a/src/main/java/com/uniovi/services/InsertSampleDataService.java +++ b/src/main/java/com/uniovi/services/InsertSampleDataService.java @@ -1,46 +1,27 @@ package com.uniovi.services; import com.uniovi.dto.PlayerDto; -import com.uniovi.entities.Question; -import com.uniovi.repositories.GameSessionRepository; -import com.uniovi.repositories.QuestionRepository; import jakarta.transaction.Transactional; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.event.EventListener; import org.springframework.core.env.Environment; import org.springframework.stereotype.Service; -import java.io.IOException; import java.util.Arrays; -import java.util.List; @Service public class InsertSampleDataService { private final PlayerService playerService; - private final QuestionService questionService; - private final CategoryService categoryService; - private final QuestionRepository questionRepository; - private final GameSessionRepository gameSessionRepository; - private Environment environment; + private final Environment environment; - private Logger log = LoggerFactory.getLogger(InsertSampleDataService.class); - - public InsertSampleDataService(PlayerService playerService, QuestionService questionService, - CategoryService categoryService, QuestionRepository questionRepository, - GameSessionRepository gameSessionRepository, Environment environment) { + public InsertSampleDataService(PlayerService playerService, Environment environment) { this.playerService = playerService; - this.questionService = questionService; - this.categoryService = categoryService; - this.questionRepository = questionRepository; - this.gameSessionRepository = gameSessionRepository; this.environment = environment; } @Transactional @EventListener(ApplicationReadyEvent.class) // Uncomment this line to insert sample data on startup - public void insertSampleQuestions() throws InterruptedException, IOException { + public void insertSampleQuestions() { if (playerService.getUserByEmail("test@test.com").isEmpty()) { PlayerDto player = new PlayerDto(); player.setEmail("test@test.com"); diff --git a/src/main/java/com/uniovi/services/PlayerService.java b/src/main/java/com/uniovi/services/PlayerService.java index fc9da433..c241de5b 100644 --- a/src/main/java/com/uniovi/services/PlayerService.java +++ b/src/main/java/com/uniovi/services/PlayerService.java @@ -2,14 +2,11 @@ import com.uniovi.dto.PlayerDto; import com.uniovi.entities.Player; -import com.uniovi.repositories.PlayerRepository; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import java.util.List; -import java.util.ArrayList; import java.util.Optional; @Service diff --git a/src/main/java/com/uniovi/services/QuestionGeneratorService.java b/src/main/java/com/uniovi/services/QuestionGeneratorService.java index e92a4ce0..4f22f40f 100644 --- a/src/main/java/com/uniovi/services/QuestionGeneratorService.java +++ b/src/main/java/com/uniovi/services/QuestionGeneratorService.java @@ -31,47 +31,44 @@ public class QuestionGeneratorService { private final QuestionService questionService; - public static final String jsonFilePath = "src/main/resources/static/JSON/QuestionTemplates.json"; + public static final String JSON_FILE_PATH = "src/main/resources/static/JSON/QuestionTemplates.json"; private Deque types = new ArrayDeque<>(); private JsonNode json; - @Autowired private Environment environment; - private Logger log = LoggerFactory.getLogger(InsertSampleDataService.class); + private final Logger log = LoggerFactory.getLogger(QuestionGeneratorService.class); private boolean started; - public QuestionGeneratorService(QuestionService questionService) { + public QuestionGeneratorService(QuestionService questionService, Environment environment) throws IOException { this.questionService = questionService; + this.environment = environment; ((QuestionServiceImpl)questionService).setQuestionGeneratorService(this); parseQuestionTypes(); this.started = true; } - private void parseQuestionTypes() { - try { - File jsonFile = new File(jsonFilePath); - ObjectMapper objectMapper = new ObjectMapper(); - json = objectMapper.readTree(jsonFile); - JsonNode categories = json.findValue("categories"); - for (JsonNode category : categories) { - String categoryName = category.get("name").textValue(); - Category cat = new Category(categoryName); - JsonNode questionsNode = category.findValue("questions"); - for (JsonNode question : questionsNode) { - types.push(new QuestionType(question, cat)); - } + private void parseQuestionTypes() throws IOException { + File jsonFile = new File(JSON_FILE_PATH); + ObjectMapper objectMapper = new ObjectMapper(); + json = objectMapper.readTree(jsonFile); + JsonNode categories = json.findValue("categories"); + for (JsonNode category : categories) { + String categoryName = category.get("name").textValue(); + Category cat = new Category(categoryName); + JsonNode questionsNode = category.findValue("questions"); + for (JsonNode question : questionsNode) { + types.push(new QuestionType(question, cat)); } - } catch (IOException e) { - throw new RuntimeException(e); } } @Scheduled(fixedRate = 86400000, initialDelay = 86400000) - public void generateAllQuestions(){ + public void generateAllQuestions() throws IOException { + resetGeneration(); } @Scheduled(fixedRate = 150000) @@ -120,14 +117,14 @@ public void generateTestQuestions() throws IOException, InterruptedException { } @Transactional - public void generateTestQuestions(String cat) throws IOException { + public void generateTestQuestions(String cat) { Answer a1 = new Answer("1", true); List answers = List.of(a1, new Answer("2", false), new Answer("3", false), new Answer("4", false)); Question q = new Question("Statement", answers, a1, new Category(cat), "es"); questionService.addNewQuestion(new QuestionDto(q)); } - public void resetGeneration() { + public void resetGeneration() throws IOException { types.clear(); parseQuestionTypes(); } diff --git a/src/main/java/com/uniovi/services/QuestionService.java b/src/main/java/com/uniovi/services/QuestionService.java index 34801782..1cea8683 100644 --- a/src/main/java/com/uniovi/services/QuestionService.java +++ b/src/main/java/com/uniovi/services/QuestionService.java @@ -7,6 +7,7 @@ import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; +import java.io.IOException; import java.util.List; import java.util.Optional; @@ -100,5 +101,5 @@ public interface QuestionService { /** * Delete all the questions */ - void deleteAllQuestions(); + void deleteAllQuestions() throws IOException; } diff --git a/src/main/java/com/uniovi/services/impl/GameSessionImpl.java b/src/main/java/com/uniovi/services/impl/GameSessionImpl.java index d7e2ad3a..97a4ab87 100644 --- a/src/main/java/com/uniovi/services/impl/GameSessionImpl.java +++ b/src/main/java/com/uniovi/services/impl/GameSessionImpl.java @@ -7,7 +7,6 @@ import com.uniovi.services.GameSessionService; import com.uniovi.services.QuestionService; import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; diff --git a/src/main/java/com/uniovi/services/impl/PlayerServiceImpl.java b/src/main/java/com/uniovi/services/impl/PlayerServiceImpl.java index 9d0fb497..64805509 100644 --- a/src/main/java/com/uniovi/services/impl/PlayerServiceImpl.java +++ b/src/main/java/com/uniovi/services/impl/PlayerServiceImpl.java @@ -6,10 +6,8 @@ import com.uniovi.entities.Associations; import com.uniovi.entities.Player; import com.uniovi.repositories.PlayerRepository; -import com.uniovi.repositories.RoleRepository; import com.uniovi.services.PlayerService; import com.uniovi.services.RoleService; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.security.crypto.password.PasswordEncoder; @@ -17,15 +15,14 @@ import com.uniovi.entities.Role; import java.util.ArrayList; -import java.util.HashSet; import java.util.List; import java.util.Optional; @Service public class PlayerServiceImpl implements PlayerService { - private PlayerRepository playerRepository; - private RoleService roleService; - private PasswordEncoder passwordEncoder; + private final PlayerRepository playerRepository; + private final RoleService roleService; + private final PasswordEncoder passwordEncoder; public PlayerServiceImpl(PlayerRepository playerRepository, RoleService roleService, PasswordEncoder passwordEncoder) { this.playerRepository = playerRepository; @@ -101,7 +98,6 @@ public List getUsersByRole(String role) { public void generateApiKey(Player player) { ApiKey apiKey = new ApiKey(); Associations.PlayerApiKey.addApiKey(player, apiKey); - System.out.println("Generated API key for " + player.getUsername() + ": " + apiKey.getKeyToken()); playerRepository.save(player); } diff --git a/src/main/java/com/uniovi/services/impl/QuestionServiceImpl.java b/src/main/java/com/uniovi/services/impl/QuestionServiceImpl.java index 163fc20a..ffe3bd3a 100644 --- a/src/main/java/com/uniovi/services/impl/QuestionServiceImpl.java +++ b/src/main/java/com/uniovi/services/impl/QuestionServiceImpl.java @@ -14,12 +14,12 @@ import jakarta.persistence.EntityManager; import jakarta.transaction.Transactional; import lombok.Setter; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; +import java.io.IOException; import java.security.SecureRandom; import java.util.ArrayList; import java.util.List; @@ -83,8 +83,7 @@ public Question addNewQuestion(QuestionDto question) { @Override public List getAllQuestions() { - List l = new ArrayList<>(questionRepository.findAll()); - return l; + return new ArrayList<>(questionRepository.findAll()); } @Override @@ -173,7 +172,7 @@ public void deleteQuestion(Long id) { } @Override - public void deleteAllQuestions() { + public void deleteAllQuestions() throws IOException { questionGeneratorService.resetGeneration(); questionRepository.deleteAll(); } diff --git a/src/main/java/com/uniovi/services/impl/RestApiServiceImpl.java b/src/main/java/com/uniovi/services/impl/RestApiServiceImpl.java index 3ff29db6..aa23abc4 100644 --- a/src/main/java/com/uniovi/services/impl/RestApiServiceImpl.java +++ b/src/main/java/com/uniovi/services/impl/RestApiServiceImpl.java @@ -59,6 +59,7 @@ public List getPlayers(Map params) { Optional found = playerService.getUser(Long.parseLong(params.get("id"))); found.ifPresent(players::add); } catch (NumberFormatException ignored) { + } } @@ -85,7 +86,7 @@ public List getPlayers(Map params) { if (!ranOtherParams) return playerService.getUsersByRole(params.get("role")); else - players.removeIf(p -> !p.getRoles().stream().anyMatch(r -> r.getName().equals(params.get("role")))); + players.removeIf(p -> p.getRoles().stream().noneMatch(r -> r.getName().equals(params.get("role")))); } return players.stream().toList();