Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,8 @@ public DuelData generateDuelData(final String lobbyId) throws DuelException {

List<QuestionBankDto> lobbyQuestions = lobbyQuestionRepository.findLobbyQuestionsByLobbyId(lobbyId).stream()
.map(lq -> questionBankRepository.getQuestionById(lq.getQuestionBankId()))
.filter(Optional::isPresent)
.map(Optional::get)
.map(QuestionBankDto::fromQuestionBank)
.collect(Collectors.toList());

Expand Down Expand Up @@ -186,7 +188,9 @@ public void startDuel(final String playerId, final boolean isAdminOverride) thro
lobby.setExpiresAt(Optional.of(StandardizedOffsetDateTime.now().plusMinutes(30)));
lobbyRepository.updateLobby(lobby);

QuestionBank randomQuestion = questionBankRepository.getRandomQuestion();
QuestionBank randomQuestion = questionBankRepository
.getRandomQuestion()
.orElseThrow(() -> new DuelException(HttpStatus.NOT_FOUND, "No questions available."));

LobbyQuestion lobbyQuestion = LobbyQuestion.builder()
.lobbyId(lobby.getId())
Expand Down Expand Up @@ -281,6 +285,8 @@ public int processSubmissions(User user, Lobby activeLobby) throws DuelException
var solvableQuestionTitlesSet = lobbyQuestions.stream()
.map(LobbyQuestion::getQuestionBankId)
.map(questionBankRepository::getQuestionById)
.filter(Optional::isPresent)
.map(Optional::get)
.map(QuestionBank::getQuestionTitle)
.collect(Collectors.toSet());

Expand Down
Comment thread
angelayu0530 marked this conversation as resolved.
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,13 @@

import java.time.OffsetDateTime;
import java.util.List;
import java.util.Optional;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.patinanetwork.codebloom.common.db.helper.annotations.JoinColumn;
import org.patinanetwork.codebloom.common.db.helper.annotations.NotNullColumn;
import org.patinanetwork.codebloom.common.db.helper.annotations.NullColumn;
import org.patinanetwork.codebloom.common.db.models.question.QuestionDifficulty;
import org.patinanetwork.codebloom.common.db.models.question.topic.QuestionTopic;

Expand All @@ -20,31 +19,23 @@
@ToString
public class QuestionBank {

@NotNullColumn
private String id;

@NotNullColumn
private String questionSlug;

@NotNullColumn
private QuestionDifficulty questionDifficulty;

@NotNullColumn
private String questionTitle;

@NotNullColumn
private int questionNumber;

@NotNullColumn
private String questionLink;

@NullColumn
private String description;
@Builder.Default
private Optional<String> description = Optional.empty();

@NotNullColumn
private float acceptanceRate;

@NotNullColumn
private OffsetDateTime createdAt;

/** Join field, update/create with {@link QuestionTopicRepository} */
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
package org.patinanetwork.codebloom.common.db.repos.question.questionbank;

import java.util.List;
import java.util.Optional;
import org.patinanetwork.codebloom.common.db.models.question.QuestionDifficulty;
import org.patinanetwork.codebloom.common.db.models.question.bank.QuestionBank;
import org.patinanetwork.codebloom.common.db.models.question.topic.LeetcodeTopicEnum;

public interface QuestionBankRepository {
void createQuestion(QuestionBank question);

QuestionBank getQuestionById(String id);
Optional<QuestionBank> getQuestionById(String id);

QuestionBank getQuestionBySlug(String slug);
Optional<QuestionBank> getQuestionBySlug(String slug);

/**
* @note - The provided object's methods will be overridden with any returned data from the database.
Expand All @@ -29,7 +30,7 @@ public interface QuestionBankRepository {

boolean deleteQuestionById(String id);

QuestionBank getRandomQuestion();
Optional<QuestionBank> getRandomQuestion();

List<QuestionBank> getQuestionsByTopic(LeetcodeTopicEnum topic);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import javax.sql.DataSource;
import org.patinanetwork.codebloom.common.db.helper.NamedPreparedStatement;
Expand Down Expand Up @@ -45,7 +46,7 @@ private QuestionBank mapResultSetToQuestion(final ResultSet rs) throws SQLExcept
.questionNumber(questionNumber)
.questionLink(questionLink)
.questionTitle(questionTitle)
.description(description)
.description(Optional.ofNullable(description))
.acceptanceRate(acceptanceRate)
.createdAt(createdAt)
.topics(questionTopicRepository.findQuestionTopicsByQuestionBankId(questionBankId))
Expand Down Expand Up @@ -79,7 +80,7 @@ public void createQuestion(final QuestionBank question) {
stmt.setInt("number", question.getQuestionNumber());
stmt.setString("link", question.getQuestionLink());
stmt.setString("title", question.getQuestionTitle());
stmt.setString("desc", question.getDescription());
stmt.setString("desc", question.getDescription().orElse(null));
stmt.setObject("ac", question.getAcceptanceRate());

stmt.executeUpdate();
Expand All @@ -89,8 +90,7 @@ public void createQuestion(final QuestionBank question) {
}

@Override
public QuestionBank getQuestionById(final String id) {
QuestionBank question = null;
public Optional<QuestionBank> getQuestionById(final String id) {
String sql = """
SELECT
id,
Expand All @@ -113,20 +113,18 @@ public QuestionBank getQuestionById(final String id) {
stmt.setObject("id", UUID.fromString(id));
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
question = mapResultSetToQuestion(rs);
return question;
return Optional.of(mapResultSetToQuestion(rs));
}
}
} catch (SQLException e) {
throw new RuntimeException("Failed to retrieve question", e);
}

return question;
return Optional.empty();
}

@Override
public QuestionBank getQuestionBySlug(final String slug) {
QuestionBank question = null;
public Optional<QuestionBank> getQuestionBySlug(final String slug) {
String sql = """
SELECT
id,
Expand All @@ -150,15 +148,14 @@ public QuestionBank getQuestionBySlug(final String slug) {
stmt.setObject("questionSlug", slug);
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
question = mapResultSetToQuestion(rs);
return question;
return Optional.of(mapResultSetToQuestion(rs));
}
}
} catch (SQLException e) {
throw new RuntimeException("Failed to retrieve question", e);
}

return question;
return Optional.empty();
}

@Override
Expand All @@ -184,7 +181,7 @@ public boolean updateQuestion(final QuestionBank inputQuestion) {
stmt.setInt("number", inputQuestion.getQuestionNumber());
stmt.setString("link", inputQuestion.getQuestionLink());
stmt.setString("title", inputQuestion.getQuestionTitle());
stmt.setString("desc", inputQuestion.getDescription());
stmt.setString("desc", inputQuestion.getDescription().orElse(null));
stmt.setObject("ac", inputQuestion.getAcceptanceRate());
stmt.setObject("id", UUID.fromString(inputQuestion.getId()));

Expand All @@ -211,8 +208,7 @@ public boolean deleteQuestionById(final String id) {
}

@Override
public QuestionBank getRandomQuestion() {
QuestionBank question = null;
public Optional<QuestionBank> getRandomQuestion() {
String sql = """
SELECT
id,
Expand All @@ -234,15 +230,14 @@ ORDER BY RANDOM()
NamedPreparedStatement stmt = new NamedPreparedStatement(conn, sql)) {
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
question = mapResultSetToQuestion(rs);
return question;
return Optional.of(mapResultSetToQuestion(rs));
}
}
} catch (SQLException e) {
throw new RuntimeException("Failed to retrieve random question", e);
}

return question;
return Optional.empty();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public static QuestionBankDto fromQuestionBank(final QuestionBank questionBank)
.questionTitle(questionBank.getQuestionTitle())
.questionNumber(questionBank.getQuestionNumber())
.questionLink(questionBank.getQuestionLink())
.description(questionBank.getDescription())
.description(questionBank.getDescription().orElse(null))
.acceptanceRate(questionBank.getAcceptanceRate())
.createdAt(questionBank.getCreatedAt())
.topics(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,26 +116,26 @@ public ArrayList<AcceptedSubmission> handleSubmissions(
.map(s -> {
String slug = s.getTitleSlug();

QuestionBank bankQuestion = questionBankRepository.getQuestionBySlug(slug);

if (bankQuestion == null) {
LeetcodeQuestion question = fast
? leetcodeClient.findQuestionBySlugFast(slug)
: leetcodeClient.findQuestionBySlug(slug);

bankQuestion = QuestionBank.builder()
.questionSlug(question.getTitleSlug())
.questionDifficulty(QuestionDifficulty.valueOf(question.getDifficulty()))
.questionTitle(question.getQuestionTitle())
.questionNumber(question.getQuestionId())
.questionLink("https://leetcode.com/problems/" + question.getTitleSlug())
.description(question.getQuestion())
.acceptanceRate(question.getAcceptanceRate())
.topics(question.getTopics().stream()
.map(SubmissionsHandler::topicTagToQuestionTopic)
.toList())
.build();
}
QuestionBank bankQuestion = questionBankRepository
.getQuestionBySlug(slug)
.orElseGet(() -> {
LeetcodeQuestion question = fast
? leetcodeClient.findQuestionBySlugFast(slug)
: leetcodeClient.findQuestionBySlug(slug);

return QuestionBank.builder()
.questionSlug(question.getTitleSlug())
.questionDifficulty(QuestionDifficulty.valueOf(question.getDifficulty()))
.questionTitle(question.getQuestionTitle())
.questionNumber(question.getQuestionId())
.questionLink("https://leetcode.com/problems/" + question.getTitleSlug())
.description(Optional.ofNullable(question.getQuestion()))
.acceptanceRate(question.getAcceptanceRate())
.topics(question.getTopics().stream()
.map(SubmissionsHandler::topicTagToQuestionTopic)
.toList())
.build();
});

return Pair.of(slug, bankQuestion);
})
Expand Down Expand Up @@ -213,7 +213,7 @@ public ArrayList<AcceptedSubmission> handleSubmissions(
.questionNumber(bankQuestion.getQuestionNumber())
.questionLink("https://leetcode.com/problems/" + bankQuestion.getQuestionSlug())
.questionTitle(bankQuestion.getQuestionTitle())
.description(Optional.ofNullable(bankQuestion.getDescription()))
.description(bankQuestion.getDescription())
.pointsAwarded(Optional.of(points))
.acceptanceRate(bankQuestion.getAcceptanceRate())
.submittedAt(leetcodeSubmission.getTimestamp())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -931,7 +931,7 @@ void testStartDuelFailsLobbyDoesNotHaveEnoughPlayersButIsAdminUser() {
when(lobbyPlayerRepository.findValidLobbyPlayerByPlayerId(eq(userId))).thenReturn(Optional.of(lobbyPlayer));
when(lobbyRepository.findLobbyById(eq(lobbyPlayer.getLobbyId()))).thenReturn(Optional.of(lobby));
when(lobbyRepository.updateLobby(any())).thenReturn(true);
when(questionBankRepository.getRandomQuestion()).thenReturn(questionBank);
when(questionBankRepository.getRandomQuestion()).thenReturn(Optional.of(questionBank));
doNothing().when(lobbyQuestionRepository).createLobbyQuestion(any());

try {
Expand Down Expand Up @@ -975,7 +975,7 @@ void testStartDuelSuccess() {
when(lobbyPlayerRepository.findValidLobbyPlayerByPlayerId(eq(userId))).thenReturn(Optional.of(lobbyPlayer));
when(lobbyRepository.findLobbyById(eq(lobbyPlayer.getLobbyId()))).thenReturn(Optional.of(lobby));
when(lobbyRepository.updateLobby(any())).thenReturn(true);
when(questionBankRepository.getRandomQuestion()).thenReturn(questionBank);
when(questionBankRepository.getRandomQuestion()).thenReturn(Optional.of(questionBank));
doNothing().when(lobbyQuestionRepository).createLobbyQuestion(any());

try {
Expand Down Expand Up @@ -1142,7 +1142,7 @@ void testStartDuelThrowsNonDuelExceptionFromLobbyQuestionRepository() {
when(lobbyPlayerRepository.findValidLobbyPlayerByPlayerId(eq(userId))).thenReturn(Optional.of(lobbyPlayer));
when(lobbyRepository.findLobbyById(eq(lobbyPlayer.getLobbyId()))).thenReturn(Optional.of(lobby));
when(lobbyRepository.updateLobby(any())).thenReturn(true);
when(questionBankRepository.getRandomQuestion()).thenReturn(questionBank);
when(questionBankRepository.getRandomQuestion()).thenReturn(Optional.of(questionBank));
doThrow(new RuntimeException("Simulated db exception"))
.when(lobbyQuestionRepository)
.createLobbyQuestion(any());
Expand Down Expand Up @@ -1399,7 +1399,7 @@ void testProcessSubmissionsSuccessful() {
.thenReturn(Optional.of(lobbyPlayer));
when(lobbyQuestionRepository.findLobbyQuestionsByLobbyId(eq(activeLobby.getId())))
.thenReturn(List.of(lobbyQuestion));
when(questionBankRepository.getQuestionById(eq(questionBank.getId()))).thenReturn(questionBank);
when(questionBankRepository.getQuestionById(eq(questionBank.getId()))).thenReturn(Optional.of(questionBank));
when(throttledLeetcodeClient.findSubmissionsByUsername(eq(user.getLeetcodeUsername()), eq(5)))
.thenReturn(List.of(leetcodeSubmission));
when(submissionsHandler.handleSubmissions(any(), eq(user), eq(true))).thenReturn(new ArrayList<>() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import static org.junit.jupiter.api.Assertions.*;

import java.util.List;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
Expand Down Expand Up @@ -42,7 +43,8 @@ void createQuestion() {
.questionNumber(1)
.questionLink("https://leetcode.com/problems/two-sum/")
.description(
"Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.")
Optional.of(
"Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target."))
.acceptanceRate(0.8f)
.build();

Expand All @@ -62,7 +64,8 @@ void cleanUp() {
@Test
@Order(1)
void testGetQuestionById() {
QuestionBank possibleTestQuestion = questionBankRepository.getQuestionById(testQuestionBank.getId());
QuestionBank possibleTestQuestion =
questionBankRepository.getQuestionById(testQuestionBank.getId()).orElse(null);

assertNotNull(possibleTestQuestion, "Retrieved question should not be null");
assertEquals(testQuestionBank.getId(), possibleTestQuestion.getId(), "Question IDs should match");
Expand All @@ -81,8 +84,9 @@ void testGetQuestionById() {
@Test
@Order(2)
void testGetQuestionBySlug() {
QuestionBank possibleTestQuestion =
questionBankRepository.getQuestionBySlug(testQuestionBank.getQuestionSlug());
QuestionBank possibleTestQuestion = questionBankRepository
.getQuestionBySlug(testQuestionBank.getQuestionSlug())
.orElse(null);

assertNotNull(possibleTestQuestion, "Retrieved question should not be null");
assertEquals(testQuestionBank.getId(), possibleTestQuestion.getId(), "Question IDs should match");
Expand Down Expand Up @@ -118,15 +122,16 @@ void testUpdateQuestion() {
fail("Failed to update question");
}

testQuestionBank = questionBankRepository.getQuestionById(testQuestionBank.getId());
testQuestionBank =
questionBankRepository.getQuestionById(testQuestionBank.getId()).orElse(null);
assertNotNull(testQuestionBank, "Updated question should not be null");
assertEquals("Updated Two Sum", testQuestionBank.getQuestionTitle(), "Question title should be updated");
}

@Test
@Order(4)
void testGetRandomQuestion() {
QuestionBank randomQuestion = questionBankRepository.getRandomQuestion();
QuestionBank randomQuestion = questionBankRepository.getRandomQuestion().orElse(null);

assertNotNull(randomQuestion, "Random question should not be null");
assertNotNull(randomQuestion.getId(), "Random question ID should not be null");
Expand Down
Loading
Loading