Skip to content
Snippets Groups Projects
Commit 1c30ba89 authored by Daniel Gerhardt's avatar Daniel Gerhardt
Browse files

Refactor repository method signatures and variable names

* Prefer ids over "foreign" domain objects.
* Consistently use final keyword for implementation parameters and
  variables.
* As a consequence, session id is used instead of the object as cache
  key for `skillquestions`, `lecturequestions`, `preparationquestions`
  and`flashcardquestions` caches.
* Rename occurances of `questionId` to `contentId`.
parent db209f2c
Branches
1 merge request!71Refactor architecture layers
Showing
with 424 additions and 428 deletions
......@@ -27,23 +27,22 @@ import java.util.List;
public interface AnswerRepository {
Answer get(String id);
Answer getMyAnswer(User me, String questionId, int piRound);
List<Answer> getAnswers(Content content, int piRound);
List<Answer> getAnswers(Content content);
List<Answer> getAllAnswers(Content content);
int getAnswerCount(Content content, int piRound);
int getTotalAnswerCountByQuestion(Content content);
int getAbstentionAnswerCount(String questionId);
List<Answer> getFreetextAnswers(String questionId, final int start, final int limit);
List<Answer> getMyAnswers(User me, Session session);
List<Answer> getAnswers(String contentId, int piRound);
List<Answer> getAllAnswers(String contentId);
int getAnswerCount(String contentId, int round);
int getTotalAnswerCountByQuestion(String contentId);
int getAbstentionAnswerCount(String contentId);
List<Answer> getFreetextAnswers(String contentId, int start, int limit);
List<Answer> getMyAnswers(User user, String sessionId);
int getTotalAnswerCount(String sessionKey);
int deleteAnswers(Content content);
int deleteAnswers(String contentId);
Answer saveAnswer(Answer answer, User user, Content content, Session session);
Answer updateAnswer(Answer answer);
void deleteAnswer(String answerId);
int countLectureQuestionAnswers(Session session);
int countPreparationQuestionAnswers(Session session);
int deleteAllQuestionsAnswers(Session session);
int deleteAllPreparationAnswers(Session session);
int deleteAllLectureAnswers(Session session);
int countLectureQuestionAnswers(String sessionId);
int countPreparationQuestionAnswers(String sessionId);
int deleteAllQuestionsAnswers(String sessionId);
int deleteAllPreparationAnswers(String sessionId);
int deleteAllLectureAnswers(String sessionId);
int[] deleteAllAnswersWithQuestions(List<Content> contents);
}
......@@ -2,21 +2,20 @@ package de.thm.arsnova.persistance;
import de.thm.arsnova.entities.Comment;
import de.thm.arsnova.entities.CommentReadingCount;
import de.thm.arsnova.entities.Session;
import de.thm.arsnova.entities.User;
import java.util.List;
public interface CommentRepository {
int getInterposedCount(String sessionKey);
CommentReadingCount getInterposedReadingCount(Session session);
CommentReadingCount getInterposedReadingCount(Session session, User user);
List<Comment> getInterposedQuestions(Session session, final int start, final int limit);
List<Comment> getInterposedQuestions(Session session, User user, final int start, final int limit);
CommentReadingCount getInterposedReadingCount(String sessionId);
CommentReadingCount getInterposedReadingCount(String sessionId, User user);
List<Comment> getInterposedQuestions(String sessionId, int start, int limit);
List<Comment> getInterposedQuestions(String sessionId, User user, int start, int limit);
Comment getInterposedQuestion(String commentId);
Comment saveQuestion(Session session, Comment comment, User user);
Comment saveQuestion(String sessionId, Comment comment, User user);
void markInterposedQuestionAsRead(Comment comment);
void deleteInterposedQuestion(Comment comment);
int deleteAllInterposedQuestions(Session session);
int deleteAllInterposedQuestions(Session session, User user);
int deleteAllInterposedQuestions(String sessionId);
int deleteAllInterposedQuestions(String sessionId, User user);
}
package de.thm.arsnova.persistance;
import de.thm.arsnova.entities.Content;
import de.thm.arsnova.entities.Session;
import de.thm.arsnova.entities.User;
import java.util.List;
......@@ -9,36 +8,36 @@ import java.util.List;
public interface ContentRepository {
List<Content> getQuestions(Object... keys);
Content getQuestion(String id);
Content saveQuestion(Session session, Content content);
List<Content> getSkillQuestionsForUsers(Session session);
List<Content> getSkillQuestionsForTeachers(Session session);
int getSkillQuestionCount(Session session);
List<String> getQuestionIds(Session session, User user);
int deleteQuestionWithAnswers(Content content);
int[] deleteAllQuestionsWithAnswers(Session session);
List<String> getUnAnsweredQuestionIds(Session session, User user);
Content saveQuestion(String sessionId, Content content);
List<Content> getSkillQuestionsForUsers(String sessionId);
List<Content> getSkillQuestionsForTeachers(String sessionId);
int getSkillQuestionCount(String sessionId);
List<String> getQuestionIds(String sessionId, User user);
int deleteQuestionWithAnswers(String contentId);
int[] deleteAllQuestionsWithAnswers(String sessionId);
List<String> getUnAnsweredQuestionIds(String sessionId, User user);
Content updateQuestion(Content content);
List<Content> getLectureQuestionsForUsers(Session session);
List<Content> getLectureQuestionsForTeachers(Session session);
List<Content> getFlashcardsForUsers(Session session);
List<Content> getFlashcardsForTeachers(Session session);
List<Content> getPreparationQuestionsForUsers(Session session);
List<Content> getPreparationQuestionsForTeachers(Session session);
List<Content> getAllSkillQuestions(Session session);
int getLectureQuestionCount(Session session);
int getFlashcardCount(Session session);
int getPreparationQuestionCount(Session session);
void publishQuestions(Session session, boolean publish, List<Content> contents);
List<Content> publishAllQuestions(Session session, boolean publish);
List<String> getQuestionIdsBySubject(Session session, String questionVariant, String subject);
List<Content> getQuestionsByIds(List<String> ids, Session session);
void resetQuestionsRoundState(Session session, List<Content> contents);
void setVotingAdmissions(Session session, boolean disableVoting, List<Content> contents);
List<Content> setVotingAdmissionForAllQuestions(Session session, boolean disableVoting);
int[] deleteAllLectureQuestionsWithAnswers(Session session);
int[] deleteAllFlashcardsWithAnswers(Session session);
int[] deleteAllPreparationQuestionsWithAnswers(Session session);
List<String> getSubjects(Session session, String questionVariant);
List<String> getUnAnsweredLectureQuestionIds(Session session, User user);
List<String> getUnAnsweredPreparationQuestionIds(Session session, User user);
List<Content> getLectureQuestionsForUsers(String sessionId);
List<Content> getLectureQuestionsForTeachers(String sessionId);
List<Content> getFlashcardsForUsers(String sessionId);
List<Content> getFlashcardsForTeachers(String sessionId);
List<Content> getPreparationQuestionsForUsers(String sessionId);
List<Content> getPreparationQuestionsForTeachers(String sessionId);
List<Content> getAllSkillQuestions(String sessionId);
int getLectureQuestionCount(String sessionId);
int getFlashcardCount(String sessionId);
int getPreparationQuestionCount(String sessionId);
void publishQuestions(String sessionId, boolean publish, List<Content> contents);
List<Content> publishAllQuestions(String sessionId, boolean publish);
List<String> getQuestionIdsBySubject(String sessionId, String questionVariant, String subject);
List<Content> getQuestionsByIds(List<String> ids);
void resetQuestionsRoundState(String sessionId, List<Content> contents);
void setVotingAdmissions(String sessionId, boolean disableVoting, List<Content> contents);
List<Content> setVotingAdmissionForAllQuestions(String sessionId, boolean disableVoting);
int[] deleteAllLectureQuestionsWithAnswers(String sessionId);
int[] deleteAllFlashcardsWithAnswers(String sessionId);
int[] deleteAllPreparationQuestionsWithAnswers(String sessionId);
List<String> getSubjects(String sessionId, String questionVariant);
List<String> getUnAnsweredLectureQuestionIds(String sessionId, User user);
List<String> getUnAnsweredPreparationQuestionIds(String sessionId, User user);
}
......@@ -41,7 +41,7 @@ public interface LogEntryRepository {
* @param payload arbitrary logging data
* @param level severity of the event
*/
default void log(String event, Map<String, Object> payload, LogEntry.LogLevel level) {
default void log(final String event, final Map<String, Object> payload, final LogEntry.LogLevel level) {
create(event, level, payload);
}
......@@ -53,7 +53,7 @@ public interface LogEntryRepository {
* @param event type of the event
* @param payload arbitrary logging data
*/
default void log(String event, Map<String, Object> payload) {
default void log(final String event, final Map<String, Object> payload) {
create(event, LogEntry.LogLevel.INFO, payload);
}
......@@ -65,7 +65,7 @@ public interface LogEntryRepository {
* @param level severity of the event
* @param rawPayload key/value pairs of arbitrary logging data
*/
default void log(String event, LogEntry.LogLevel level, Object... rawPayload) {
default void log(final String event, final LogEntry.LogLevel level, final Object... rawPayload) {
if (rawPayload.length % 2 != 0) {
throw new IllegalArgumentException("");
}
......@@ -84,7 +84,7 @@ public interface LogEntryRepository {
* @param event type of the event
* @param rawPayload key/value pairs of arbitrary logging data
*/
default void log(String event, Object... rawPayload) {
default void log(final String event, final Object... rawPayload) {
log(event, LogEntry.LogLevel.INFO, rawPayload);
}
}
......@@ -3,6 +3,6 @@ package de.thm.arsnova.persistance;
import de.thm.arsnova.entities.MotdList;
public interface MotdListRepository {
MotdList getMotdListForUser(final String username);
MotdList getMotdListForUser(String username);
MotdList createOrUpdateMotdList(MotdList motdlist);
}
......@@ -27,7 +27,7 @@ public interface MotdRepository {
List<Motd> getMotdsForLoggedIn();
List<Motd> getMotdsForTutors();
List<Motd> getMotdsForStudents();
List<Motd> getMotdsForSession(final String sessionkey);
List<Motd> getMotdsForSession(String sessionkey);
Motd getMotdByKey(String key);
Motd createOrUpdateMotd(Motd motd);
boolean deleteMotd(Motd motd);
......
......@@ -41,19 +41,19 @@ public interface SessionRepository {
Session changeSessionCreator(Session session, String newCreator);
int[] deleteInactiveGuestSessions(long lastActivityBefore);
List<Session> getMySessions(User user, final int start, final int limit);
List<Session> getSessionsForUsername(String username, final int start, final int limit);
List<Session> getMySessions(User user, int start, int limit);
List<Session> getSessionsForUsername(String username, int start, int limit);
List<Session> getPublicPoolSessions();
List<Session> getMyPublicPoolSessions(User user);
boolean sessionKeyAvailable(String keyword);
Session updateSessionOwnerActivity(Session session);
List<Session> getVisitedSessionsForUsername(String username, final int start, final int limit);
List<SessionInfo> getMySessionsInfo(User user, final int start, final int limit);
List<Session> getVisitedSessionsForUsername(String username, int start, int limit);
List<SessionInfo> getMySessionsInfo(User user, int start, int limit);
List<SessionInfo> getPublicPoolSessionsInfo();
List<SessionInfo> getMyPublicPoolSessionsInfo(final User user);
List<SessionInfo> getMyVisitedSessionsInfo(User currentUser, final int start, final int limit);
List<SessionInfo> getMyPublicPoolSessionsInfo(User user);
List<SessionInfo> getMyVisitedSessionsInfo(User currentUser, int start, int limit);
List<Session> getCourseSessions(List<Course> courses);
SessionInfo importSession(User user, ImportExportSession importSession);
ImportExportSession exportSession(String sessionkey, Boolean withAnswer, Boolean withFeedbackQuestions);
LoggedIn registerAsOnlineUser(final User user, final Session session);
LoggedIn registerAsOnlineUser(User user, Session session);
}
......@@ -25,7 +25,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.scheduling.annotation.Scheduled;
......@@ -34,6 +33,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.stream.Collectors;
public class CouchDbAnswerRepository extends CouchDbRepositorySupport<Answer> implements AnswerRepository, ApplicationEventPublisherAware {
private static final int BULK_PARTITION_SIZE = 500;
......@@ -52,7 +52,7 @@ public class CouchDbAnswerRepository extends CouchDbRepositorySupport<Answer> im
private ApplicationEventPublisher publisher;
public CouchDbAnswerRepository(CouchDbConnector db, boolean createIfNotExists) {
public CouchDbAnswerRepository(final CouchDbConnector db, final boolean createIfNotExists) {
super(Answer.class, db, createIfNotExists);
}
......@@ -78,32 +78,32 @@ public class CouchDbAnswerRepository extends CouchDbRepositorySupport<Answer> im
for (AnswerQueueElement e : elements) {
this.publisher.publishEvent(new NewAnswerEvent(this, e.getSession(), e.getAnswer(), e.getUser(), e.getQuestion()));
}
} catch (DbAccessException e) {
} catch (final DbAccessException e) {
logger.error("Could not bulk save answers from queue.", e);
}
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
public void setApplicationEventPublisher(final ApplicationEventPublisher publisher) {
this.publisher = publisher;
}
@CacheEvict("answers")
@Override
public int deleteAnswers(final Content content) {
public int deleteAnswers(final String contentId) {
try {
final ViewResult result = db.queryView(createQuery("by_questionid")
.key(content.getId()));
.key(contentId));
final List<List<ViewResult.Row>> partitions = Lists.partition(result.getRows(), BULK_PARTITION_SIZE);
int count = 0;
for (List<ViewResult.Row> partition: partitions) {
List<BulkDeleteDocument> answersToDelete = new ArrayList<>();
for (final List<ViewResult.Row> partition: partitions) {
final List<BulkDeleteDocument> answersToDelete = new ArrayList<>();
for (final ViewResult.Row a : partition) {
final BulkDeleteDocument d = new BulkDeleteDocument(a.getId(), a.getValueAsNode().get("_rev").asText());
answersToDelete.add(d);
}
List<DocumentOperationResult> errors = db.executeBulk(answersToDelete);
final List<DocumentOperationResult> errors = db.executeBulk(answersToDelete);
count += partition.size() - errors.size();
if (errors.size() > 0) {
logger.error("Could not bulk delete {} of {} answers.", errors.size(), partition.size());
......@@ -113,29 +113,29 @@ public class CouchDbAnswerRepository extends CouchDbRepositorySupport<Answer> im
return count;
} catch (final DbAccessException e) {
logger.error("Could not delete answers for content {}.", content.getId(), e);
logger.error("Could not delete answers for content {}.", contentId, e);
}
return 0;
}
@Override
public Answer getMyAnswer(final User me, final String questionId, final int piRound) {
public Answer getMyAnswer(final User me, final String contentId, final int piRound) {
final List<Answer> answerList = queryView("by_questionid_user_piround",
ComplexKey.of(questionId, me.getUsername(), piRound));
ComplexKey.of(contentId, me.getUsername(), piRound));
return answerList.isEmpty() ? null : answerList.get(0);
}
@Override
public List<Answer> getAnswers(final Content content, final int piRound) {
final String questionId = content.getId();
public List<Answer> getAnswers(final String contentId, final int piRound) {
final String questionId = contentId;
final ViewResult result = db.queryView(createQuery("by_questionid_piround_text_subject")
.group(true)
.startKey(ComplexKey.of(questionId, piRound))
.endKey(ComplexKey.of(questionId, piRound, ComplexKey.emptyObject())));
final int abstentionCount = getAbstentionAnswerCount(questionId);
List<Answer> answers = new ArrayList<>();
final List<Answer> answers = new ArrayList<>();
for (final ViewResult.Row d : result) {
final Answer a = new Answer();
a.setAnswerCount(d.getValueAsInt());
......@@ -151,13 +151,12 @@ public class CouchDbAnswerRepository extends CouchDbRepositorySupport<Answer> im
}
@Override
public List<Answer> getAllAnswers(final Content content) {
final String questionId = content.getId();
public List<Answer> getAllAnswers(final String contentId) {
final ViewResult result = db.queryView(createQuery("by_questionid_piround_text_subject")
.group(true)
.startKey(ComplexKey.of(questionId))
.endKey(ComplexKey.of(questionId, ComplexKey.emptyObject())));
final int abstentionCount = getAbstentionAnswerCount(questionId);
.startKey(ComplexKey.of(contentId))
.endKey(ComplexKey.of(contentId, ComplexKey.emptyObject())));
final int abstentionCount = getAbstentionAnswerCount(contentId);
final List<Answer> answers = new ArrayList<>();
for (final ViewResult.Row d : result.getRows()) {
......@@ -177,44 +176,38 @@ public class CouchDbAnswerRepository extends CouchDbRepositorySupport<Answer> im
return answers;
}
@Cacheable("answers")
@Override
public List<Answer> getAnswers(final Content content) {
return this.getAnswers(content, content.getPiRound());
}
@Override
public int getAbstentionAnswerCount(final String questionId) {
public int getAbstentionAnswerCount(final String contentId) {
final ViewResult result = db.queryView(createQuery("by_questionid_piround_text_subject")
//.group(true)
.startKey(ComplexKey.of(questionId))
.endKey(ComplexKey.of(questionId, ComplexKey.emptyObject())));
.startKey(ComplexKey.of(contentId))
.endKey(ComplexKey.of(contentId, ComplexKey.emptyObject())));
return result.isEmpty() ? 0 : result.getRows().get(0).getValueAsInt();
}
@Override
public int getAnswerCount(final Content content, final int piRound) {
public int getAnswerCount(final String contentId, final int round) {
final ViewResult result = db.queryView(createQuery("by_questionid_piround_text_subject")
//.group(true)
.startKey(ComplexKey.of(content.getId(), piRound))
.endKey(ComplexKey.of(content.getId(), piRound, ComplexKey.emptyObject())));
.startKey(ComplexKey.of(contentId, round))
.endKey(ComplexKey.of(contentId, round, ComplexKey.emptyObject())));
return result.isEmpty() ? 0 : result.getRows().get(0).getValueAsInt();
}
@Override
public int getTotalAnswerCountByQuestion(final Content content) {
public int getTotalAnswerCountByQuestion(final String contentId) {
final ViewResult result = db.queryView(createQuery("by_questionid_piround_text_subject")
//.group(true)
.startKey(ComplexKey.of(content.getId()))
.endKey(ComplexKey.of(content.getId(), ComplexKey.emptyObject())));
.startKey(ComplexKey.of(contentId))
.endKey(ComplexKey.of(contentId, ComplexKey.emptyObject())));
return result.isEmpty() ? 0 : result.getRows().get(0).getValueAsInt();
}
@Override
public List<Answer> getFreetextAnswers(final String questionId, final int start, final int limit) {
public List<Answer> getFreetextAnswers(final String contentId, final int start, final int limit) {
final int qSkip = start > 0 ? start : -1;
final int qLimit = limit > 0 ? limit : -1;
......@@ -222,8 +215,8 @@ public class CouchDbAnswerRepository extends CouchDbRepositorySupport<Answer> im
.skip(qSkip)
.limit(qLimit)
//.includeDocs(true)
.startKey(ComplexKey.of(questionId))
.endKey(ComplexKey.of(questionId, ComplexKey.emptyObject()))
.startKey(ComplexKey.of(contentId))
.endKey(ComplexKey.of(contentId, ComplexKey.emptyObject()))
.descending(true),
Answer.class);
......@@ -231,8 +224,8 @@ public class CouchDbAnswerRepository extends CouchDbRepositorySupport<Answer> im
}
@Override
public List<Answer> getMyAnswers(final User me, final Session s) {
return queryView("by_user_sessionid", ComplexKey.of(me.getUsername(), s.getId()));
public List<Answer> getMyAnswers(final User user, final String sessionId) {
return queryView("by_user_sessionid", ComplexKey.of(user.getUsername(), sessionId));
}
@Override
......@@ -283,18 +276,18 @@ public class CouchDbAnswerRepository extends CouchDbRepositorySupport<Answer> im
}
@Override
public int countLectureQuestionAnswers(final Session session) {
return countQuestionVariantAnswers(session, "lecture");
public int countLectureQuestionAnswers(final String sessionId) {
return countQuestionVariantAnswers(sessionId, "lecture");
}
@Override
public int countPreparationQuestionAnswers(final Session session) {
return countQuestionVariantAnswers(session, "preparation");
public int countPreparationQuestionAnswers(final String sessionId) {
return countQuestionVariantAnswers(sessionId, "preparation");
}
private int countQuestionVariantAnswers(final Session session, final String variant) {
private int countQuestionVariantAnswers(final String sessionId, final String variant) {
final ViewResult result = db.queryView(createQuery("by_sessionid_variant")
.key(ComplexKey.of(session.getId(), variant)));
.key(ComplexKey.of(sessionId, variant)));
return result.isEmpty() ? 0 : result.getRows().get(0).getValueAsInt();
}
......@@ -302,60 +295,60 @@ public class CouchDbAnswerRepository extends CouchDbRepositorySupport<Answer> im
/* TODO: Only evict cache entry for the answer's question. This requires some refactoring. */
@CacheEvict(value = "answers", allEntries = true)
@Override
public int deleteAllQuestionsAnswers(final Session session) {
final List<Content> contents = contentRepository.getQuestions(session.getId());
contentRepository.resetQuestionsRoundState(session, contents);
public int deleteAllQuestionsAnswers(final String sessionId) {
final List<Content> contents = contentRepository.getQuestions(sessionId);
contentRepository.resetQuestionsRoundState(sessionId, contents);
final List<String> contentIds = contents.stream().map(Content::getId).collect(Collectors.toList());
return deleteAllAnswersForQuestions(contents);
return deleteAllAnswersForQuestions(contentIds);
}
/* TODO: Only evict cache entry for the answer's question. This requires some refactoring. */
@CacheEvict(value = "answers", allEntries = true)
@Override
public int deleteAllPreparationAnswers(final Session session) {
final List<Content> contents = contentRepository.getQuestions(session.getId(), "preparation");
contentRepository.resetQuestionsRoundState(session, contents);
public int deleteAllPreparationAnswers(final String sessionId) {
final List<Content> contents = contentRepository.getQuestions(sessionId, "preparation");
contentRepository.resetQuestionsRoundState(sessionId, contents);
final List<String> contentIds = contents.stream().map(Content::getId).collect(Collectors.toList());
return deleteAllAnswersForQuestions(contents);
return deleteAllAnswersForQuestions(contentIds);
}
/* TODO: Only evict cache entry for the answer's question. This requires some refactoring. */
@CacheEvict(value = "answers", allEntries = true)
@Override
public int deleteAllLectureAnswers(final Session session) {
final List<Content> contents = contentRepository.getQuestions(session.getId(), "lecture");
contentRepository.resetQuestionsRoundState(session, contents);
public int deleteAllLectureAnswers(final String sessionId) {
final List<Content> contents = contentRepository.getQuestions(sessionId, "lecture");
contentRepository.resetQuestionsRoundState(sessionId, contents);
final List<String> contentIds = contents.stream().map(Content::getId).collect(Collectors.toList());
return deleteAllAnswersForQuestions(contents);
return deleteAllAnswersForQuestions(contentIds);
}
public int deleteAllAnswersForQuestions(List<Content> contents) {
List<String> questionIds = new ArrayList<>();
for (Content q : contents) {
questionIds.add(q.getId());
}
public int deleteAllAnswersForQuestions(final List<String> contentIds) {
final ViewResult result = db.queryView(createQuery("by_questionid")
.keys(questionIds));
.keys(contentIds));
final List<BulkDeleteDocument> allAnswers = new ArrayList<>();
for (ViewResult.Row a : result.getRows()) {
for (final ViewResult.Row a : result.getRows()) {
final BulkDeleteDocument d = new BulkDeleteDocument(a.getId(), a.getValueAsNode().get("_rev").asText());
allAnswers.add(d);
}
try {
List<DocumentOperationResult> errors = db.executeBulk(allAnswers);
final List<DocumentOperationResult> errors = db.executeBulk(allAnswers);
return allAnswers.size() - errors.size();
} catch (DbAccessException e) {
} catch (final DbAccessException e) {
logger.error("Could not bulk delete answers.", e);
}
return 0;
}
public int[] deleteAllAnswersWithQuestions(List<Content> contents) {
/* TODO: Split up - the combined action should be handled on the service level. */
public int[] deleteAllAnswersWithQuestions(final List<Content> contents) {
List<String> questionIds = new ArrayList<>();
final List<BulkDeleteDocument> allQuestions = new ArrayList<>();
for (Content q : contents) {
for (final Content q : contents) {
final BulkDeleteDocument d = new BulkDeleteDocument(q.getId(), q.getRevision());
questionIds.add(q.getId());
allQuestions.add(d);
......@@ -364,19 +357,19 @@ public class CouchDbAnswerRepository extends CouchDbRepositorySupport<Answer> im
final ViewResult result = db.queryView(createQuery("by_questionid")
.key(questionIds));
final List<BulkDeleteDocument> allAnswers = new ArrayList<>();
for (ViewResult.Row a : result.getRows()) {
for (final ViewResult.Row a : result.getRows()) {
final BulkDeleteDocument d = new BulkDeleteDocument(a.getId(), a.getValueAsNode().get("_rev").asText());
allAnswers.add(d);
}
try {
List<BulkDeleteDocument> deleteList = new ArrayList<>(allAnswers);
final List<BulkDeleteDocument> deleteList = new ArrayList<>(allAnswers);
deleteList.addAll(allQuestions);
List<DocumentOperationResult> errors = db.executeBulk(deleteList);
final List<DocumentOperationResult> errors = db.executeBulk(deleteList);
/* TODO: subtract errors from count */
return new int[] {allQuestions.size(), allAnswers.size()};
} catch (DbAccessException e) {
} catch (final DbAccessException e) {
logger.error("Could not bulk delete contents and answers.", e);
}
......
......@@ -30,7 +30,7 @@ public class CouchDbCommentRepository extends CouchDbRepositorySupport<Comment>
@Autowired
private SessionRepository sessionRepository;
public CouchDbCommentRepository(CouchDbConnector db, boolean createIfNotExists) {
public CouchDbCommentRepository(final CouchDbConnector db, final boolean createIfNotExists) {
super(Comment.class, db, createIfNotExists);
}
......@@ -50,19 +50,19 @@ public class CouchDbCommentRepository extends CouchDbRepositorySupport<Comment>
}
@Override
public CommentReadingCount getInterposedReadingCount(final Session session) {
public CommentReadingCount getInterposedReadingCount(final String sessionId) {
final ViewResult result = db.queryView(createQuery("by_sessionid_read")
.startKey(ComplexKey.of(session.getId()))
.endKey(ComplexKey.of(session.getId(), ComplexKey.emptyObject()))
.startKey(ComplexKey.of(sessionId))
.endKey(ComplexKey.of(sessionId, ComplexKey.emptyObject()))
.group(true));
return getInterposedReadingCount(result);
}
@Override
public CommentReadingCount getInterposedReadingCount(final Session session, final User user) {
public CommentReadingCount getInterposedReadingCount(final String sessionId, final User user) {
final ViewResult result = db.queryView(createQuery("by_sessionid_creator_read")
.startKey(ComplexKey.of(session.getId(), user.getUsername()))
.endKey(ComplexKey.of(session.getId(), user.getUsername(), ComplexKey.emptyObject()))
.startKey(ComplexKey.of(sessionId, user.getUsername()))
.endKey(ComplexKey.of(sessionId, user.getUsername(), ComplexKey.emptyObject()))
.group(true));
return getInterposedReadingCount(result);
}
......@@ -111,7 +111,7 @@ public class CouchDbCommentRepository extends CouchDbRepositorySupport<Comment>
}
@Override
public List<Comment> getInterposedQuestions(final Session session, final int start, final int limit) {
public List<Comment> getInterposedQuestions(final String sessionId, final int start, final int limit) {
final int qSkip = start > 0 ? start : -1;
final int qLimit = limit > 0 ? limit : -1;
......@@ -119,8 +119,8 @@ public class CouchDbCommentRepository extends CouchDbRepositorySupport<Comment>
.skip(qSkip)
.limit(qLimit)
.descending(true)
.startKey(ComplexKey.of(session.getId(), ComplexKey.emptyObject()))
.endKey(ComplexKey.of(session.getId()))
.startKey(ComplexKey.of(sessionId, ComplexKey.emptyObject()))
.endKey(ComplexKey.of(sessionId))
.includeDocs(true),
Comment.class);
// for (Comment comment : comments) {
......@@ -131,7 +131,7 @@ public class CouchDbCommentRepository extends CouchDbRepositorySupport<Comment>
}
@Override
public List<Comment> getInterposedQuestions(final Session session, final User user, final int start, final int limit) {
public List<Comment> getInterposedQuestions(final String sessionId, final User user, final int start, final int limit) {
final int qSkip = start > 0 ? start : -1;
final int qLimit = limit > 0 ? limit : -1;
......@@ -139,8 +139,8 @@ public class CouchDbCommentRepository extends CouchDbRepositorySupport<Comment>
.skip(qSkip)
.limit(qLimit)
.descending(true)
.startKey(ComplexKey.of(session.getId(), user.getUsername(), ComplexKey.emptyObject()))
.endKey(ComplexKey.of(session.getId(), user.getUsername()))
.startKey(ComplexKey.of(sessionId, user.getUsername(), ComplexKey.emptyObject()))
.endKey(ComplexKey.of(sessionId, user.getUsername()))
.includeDocs(true),
Comment.class);
// for (Comment comment : comments) {
......@@ -164,8 +164,9 @@ public class CouchDbCommentRepository extends CouchDbRepositorySupport<Comment>
}
@Override
public Comment saveQuestion(final Session session, final Comment comment, User user) {
comment.setSessionId(session.getId());
public Comment saveQuestion(final String sessionId, final Comment comment, final User user) {
/* TODO: This should be done on the service level. */
comment.setSessionId(sessionId);
comment.setCreator(user.getUsername());
comment.setRead(false);
if (comment.getTimestamp() == 0) {
......@@ -203,22 +204,22 @@ public class CouchDbCommentRepository extends CouchDbRepositorySupport<Comment>
}
@Override
public int deleteAllInterposedQuestions(final Session session) {
final ViewResult result = db.queryView(createQuery("by_sessionid").key(session.getId()));
public int deleteAllInterposedQuestions(final String sessionId) {
final ViewResult result = db.queryView(createQuery("by_sessionid").key(sessionId));
return deleteAllInterposedQuestions(session, result);
return deleteAllInterposedQuestions(sessionId, result);
}
@Override
public int deleteAllInterposedQuestions(final Session session, final User user) {
public int deleteAllInterposedQuestions(final String sessionId, final User user) {
final ViewResult result = db.queryView(createQuery("by_sessionid_creator_read")
.startKey(ComplexKey.of(session.getId(), user.getUsername()))
.endKey(ComplexKey.of(session.getId(), user.getUsername(), ComplexKey.emptyObject())));
.startKey(ComplexKey.of(sessionId, user.getUsername()))
.endKey(ComplexKey.of(sessionId, user.getUsername(), ComplexKey.emptyObject())));
return deleteAllInterposedQuestions(session, result);
return deleteAllInterposedQuestions(sessionId, result);
}
private int deleteAllInterposedQuestions(final Session session, final ViewResult comments) {
private int deleteAllInterposedQuestions(final String sessionId, final ViewResult comments) {
if (comments.isEmpty()) {
return 0;
}
......@@ -227,7 +228,7 @@ public class CouchDbCommentRepository extends CouchDbRepositorySupport<Comment>
try {
db.delete(row.getId(), row.getValueAsNode().get("rev").asText());
} catch (final UpdateConflictException e) {
logger.error("Could not delete all comments {}.", session, e);
logger.error("Could not delete all comments {}.", sessionId, e);
}
}
......
......@@ -29,13 +29,13 @@ import java.util.Map;
public class CouchDbLogEntryRepository extends CouchDbRepositorySupport<LogEntry> implements LogEntryRepository {
private static final Logger logger = LoggerFactory.getLogger(CouchDbLogEntryRepository.class);
public CouchDbLogEntryRepository(CouchDbConnector db, boolean createIfNotExists) {
public CouchDbLogEntryRepository(final CouchDbConnector db, final boolean createIfNotExists) {
super(LogEntry.class, db, createIfNotExists);
}
@Override
public void create(String event, LogEntry.LogLevel level, Map<String, Object> payload) {
LogEntry log = new LogEntry(event, level.ordinal(), payload);
public void create(final String event, final LogEntry.LogLevel level, final Map<String, Object> payload) {
final LogEntry log = new LogEntry(event, level.ordinal(), payload);
try {
db.create(log);
} catch (final IllegalArgumentException e) {
......
......@@ -15,20 +15,20 @@ import java.util.List;
public class CouchDbMotdListRepository extends CouchDbRepositorySupport<MotdList> implements MotdListRepository {
private static final Logger logger = LoggerFactory.getLogger(CouchDbMotdListRepository.class);
public CouchDbMotdListRepository(CouchDbConnector db, boolean createIfNotExists) {
public CouchDbMotdListRepository(final CouchDbConnector db, final boolean createIfNotExists) {
super(MotdList.class, db, createIfNotExists);
}
@Override
@Cacheable(cacheNames = "motdlist", key = "#p0")
public MotdList getMotdListForUser(final String username) {
List<MotdList> motdListList = queryView("by_username", username);
final List<MotdList> motdListList = queryView("by_username", username);
return motdListList.isEmpty() ? new MotdList() : motdListList.get(0);
}
@Override
@CachePut(cacheNames = "motdlist", key = "#p0.username")
public MotdList createOrUpdateMotdList(MotdList motdlist) {
public MotdList createOrUpdateMotdList(final MotdList motdlist) {
try {
if (motdlist.getId() != null) {
update(motdlist);
......@@ -37,7 +37,7 @@ public class CouchDbMotdListRepository extends CouchDbRepositorySupport<MotdList
}
return motdlist;
} catch (DbAccessException e) {
} catch (final DbAccessException e) {
logger.error("Could not save MotD list {}.", motdlist, e);
}
......
......@@ -37,7 +37,7 @@ public class CouchDbMotdRepository extends CouchDbRepositorySupport<Motd> implem
@Autowired
private SessionService sessionService;
public CouchDbMotdRepository(CouchDbConnector db, boolean createIfNotExists) {
public CouchDbMotdRepository(final CouchDbConnector db, final boolean createIfNotExists) {
super(Motd.class, db, createIfNotExists);
}
......@@ -84,22 +84,22 @@ public class CouchDbMotdRepository extends CouchDbRepositorySupport<Motd> implem
return getMotds("by_sessionkey", sessionkey);
}
private List<Motd> getMotds(String viewName, String key) {
private List<Motd> getMotds(final String viewName, final String key) {
return queryView(viewName, key);
}
@Override
public Motd getMotdByKey(String key) {
List<Motd> motd = queryView("by_motdkey", key);
public Motd getMotdByKey(final String key) {
final List<Motd> motd = queryView("by_motdkey", key);
return motd.get(0);
}
@Override
@CacheEvict(cacheNames = "motds", key = "#p0.audience.concat(#p0.sessionkey)")
public Motd createOrUpdateMotd(Motd motd) {
String id = motd.getId();
String rev = motd.getRevision();
public Motd createOrUpdateMotd(final Motd motd) {
final String id = motd.getId();
final String rev = motd.getRevision();
if (null != id) {
Motd oldMotd = get(id);
......@@ -115,7 +115,7 @@ public class CouchDbMotdRepository extends CouchDbRepositorySupport<Motd> implem
@Override
@CacheEvict(cacheNames = "motds", key = "#p0.audience.concat(#p0.sessionkey)")
public boolean deleteMotd(Motd motd) {
public boolean deleteMotd(final Motd motd) {
return db.delete(motd) != null;
}
}
......@@ -11,7 +11,7 @@ import org.ektorp.support.CouchDbRepositorySupport;
import org.springframework.cache.annotation.Cacheable;
public class CouchDbSessionStatisticsRepository extends CouchDbRepositorySupport implements SessionStatisticsRepository {
public CouchDbSessionStatisticsRepository(CouchDbConnector db, boolean createIfNotExists) {
public CouchDbSessionStatisticsRepository(final CouchDbConnector db, final boolean createIfNotExists) {
super(Object.class, db, "learning_progress", createIfNotExists);
}
......@@ -33,21 +33,21 @@ public class CouchDbSessionStatisticsRepository extends CouchDbRepositorySupport
// collect mapping (questionId -> max value)
for (ViewResult.Row row : maximumValueResult) {
final String questionId = row.getKeyAsNode().get(1).asText();
final String contentId = row.getKeyAsNode().get(1).asText();
final JsonNode value = row.getValueAsNode();
final int questionScore = value.get("value").asInt();
final String questionVariant = value.get("questionVariant").asText();
final int piRound = value.get("piRound").asInt();
courseScore.addQuestion(questionId, questionVariant, piRound, questionScore);
courseScore.addQuestion(contentId, questionVariant, piRound, questionScore);
}
// collect mapping (questionId -> (user -> value))
for (ViewResult.Row row : answerSumResult) {
final String username = row.getKeyAsNode().get(1).asText();
final JsonNode value = row.getValueAsNode();
final String questionId = value.get("questionId").asText();
final String contentId = value.get("questionId").asText();
final int userscore = value.get("score").asInt();
final int piRound = value.get("piRound").asInt();
courseScore.addAnswer(questionId, piRound, username, userscore);
courseScore.addAnswer(contentId, piRound, username, userscore);
}
return courseScore;
}
......
......@@ -16,7 +16,7 @@ import java.util.Set;
public class CouchDbStatisticsRepository extends CouchDbRepositorySupport implements StatisticsRepository {
private static final Logger logger = LoggerFactory.getLogger(CouchDbStatisticsRepository.class);
public CouchDbStatisticsRepository(CouchDbConnector db, boolean createIfNotExists) {
public CouchDbStatisticsRepository(final CouchDbConnector db, final boolean createIfNotExists) {
super(Object.class, db, "statistics", createIfNotExists);
}
......@@ -30,7 +30,7 @@ public class CouchDbStatisticsRepository extends CouchDbRepositorySupport implem
final ViewResult studentUserResult = db.queryView(createQuery("active_student_users").group(true));
if (!statsResult.isEmpty()) {
for (ViewResult.Row row: statsResult.getRows()) {
for (final ViewResult.Row row: statsResult.getRows()) {
final int value = row.getValueAsInt();
switch (row.getKey()) {
case "openSessions":
......@@ -65,14 +65,14 @@ public class CouchDbStatisticsRepository extends CouchDbRepositorySupport implem
}
}
if (!creatorResult.isEmpty()) {
Set<String> creators = new HashSet<>();
final Set<String> creators = new HashSet<>();
for (ViewResult.Row row: statsResult.getRows()) {
creators.add(row.getKey());
}
stats.setCreators(creators.size());
}
if (!studentUserResult.isEmpty()) {
Set<String> students = new HashSet<>();
final Set<String> students = new HashSet<>();
for (ViewResult.Row row: statsResult.getRows()) {
students.add(row.getKey());
}
......
......@@ -37,7 +37,7 @@ public class CouchDbUserRepository extends CouchDbRepositorySupport<DbUser> impl
private static final Logger logger = LoggerFactory.getLogger(CouchDbUserRepository.class);
public CouchDbUserRepository(CouchDbConnector db, boolean createIfNotExists) {
public CouchDbUserRepository(final CouchDbConnector db, final boolean createIfNotExists) {
super(DbUser.class, db, createIfNotExists);
}
......@@ -47,7 +47,7 @@ public class CouchDbUserRepository extends CouchDbRepositorySupport<DbUser> impl
@Override
public DbUser createOrUpdateUser(final DbUser user) {
String id = user.getId();
final String id = user.getId();
if (null != id) {
db.update(user);
......@@ -59,8 +59,8 @@ public class CouchDbUserRepository extends CouchDbRepositorySupport<DbUser> impl
}
@Override
public DbUser findUserByUsername(String username) {
List<DbUser> users = queryView("by_username", username);
public DbUser findUserByUsername(final String username) {
final List<DbUser> users = queryView("by_username", username);
return !users.isEmpty() ? users.get(0) : null;
}
......@@ -77,22 +77,22 @@ public class CouchDbUserRepository extends CouchDbRepositorySupport<DbUser> impl
}
@Override
public int deleteInactiveUsers(long lastActivityBefore) {
ViewQuery q = createQuery("by_creation_for_inactive").endKey(lastActivityBefore);
List<ViewResult.Row> rows = db.queryView(q).getRows();
public int deleteInactiveUsers(final long lastActivityBefore) {
final ViewQuery q = createQuery("by_creation_for_inactive").endKey(lastActivityBefore);
final List<ViewResult.Row> rows = db.queryView(q).getRows();
int count = 0;
final List<List<ViewResult.Row>> partitions = Lists.partition(rows, BULK_PARTITION_SIZE);
for (List<ViewResult.Row> partition: partitions) {
for (final List<ViewResult.Row> partition: partitions) {
final List<BulkDeleteDocument> newDocs = new ArrayList<>();
for (ViewResult.Row oldDoc : partition) {
for (final ViewResult.Row oldDoc : partition) {
final BulkDeleteDocument newDoc = new BulkDeleteDocument(oldDoc.getId(), oldDoc.getValue());
newDocs.add(newDoc);
logger.debug("Marked user document {} for deletion.", oldDoc.getId());
}
if (newDocs.size() > 0) {
List<DocumentOperationResult> results = db.executeBulk(newDocs);
final List<DocumentOperationResult> results = db.executeBulk(newDocs);
if (!results.isEmpty()) {
/* TODO: This condition should be improved so that it checks the operation results. */
count += newDocs.size();
......
......@@ -25,18 +25,18 @@ public class CouchDbVisitedSessionRepository extends CouchDbRepositorySupport<Vi
@Autowired
private LogEntryRepository dbLogger;
public CouchDbVisitedSessionRepository(CouchDbConnector db, boolean createIfNotExists) {
public CouchDbVisitedSessionRepository(final CouchDbConnector db, final boolean createIfNotExists) {
super(VisitedSession.class, db, createIfNotExists);
}
@Override
public int deleteInactiveGuestVisitedSessionLists(long lastActivityBefore) {
public int deleteInactiveGuestVisitedSessionLists(final long lastActivityBefore) {
try {
ViewResult result = db.queryView(createQuery("by_last_activity_for_guests").endKey(lastActivityBefore));
final ViewResult result = db.queryView(createQuery("by_last_activity_for_guests").endKey(lastActivityBefore));
int count = 0;
List<List<ViewResult.Row>> partitions = Lists.partition(result.getRows(), BULK_PARTITION_SIZE);
for (List<ViewResult.Row> partition: partitions) {
final List<List<ViewResult.Row>> partitions = Lists.partition(result.getRows(), BULK_PARTITION_SIZE);
for (final List<ViewResult.Row> partition: partitions) {
final List<BulkDeleteDocument> newDocs = new ArrayList<>();
for (final ViewResult.Row oldDoc : partition) {
final BulkDeleteDocument newDoc = new BulkDeleteDocument(oldDoc.getId(), oldDoc.getValueAsNode().get("_rev").asText());
......@@ -47,7 +47,7 @@ public class CouchDbVisitedSessionRepository extends CouchDbRepositorySupport<Vi
}
if (!newDocs.isEmpty()) {
List<DocumentOperationResult> results = db.executeBulk(newDocs);
final List<DocumentOperationResult> results = db.executeBulk(newDocs);
count += newDocs.size() - results.size();
if (!results.isEmpty()) {
logger.error("Could not bulk delete some visited session lists.");
......@@ -61,7 +61,7 @@ public class CouchDbVisitedSessionRepository extends CouchDbRepositorySupport<Vi
}
return count;
} catch (DbAccessException e) {
} catch (final DbAccessException e) {
logger.error("Could not delete visited session lists of inactive users.", e);
}
......
......@@ -30,11 +30,11 @@ public class InitializingCouchDbConnector extends StdCouchDbConnector implements
private ResourceLoader resourceLoader;
public InitializingCouchDbConnector(String databaseName, CouchDbInstance dbInstance) {
public InitializingCouchDbConnector(final String databaseName, final CouchDbInstance dbInstance) {
super(databaseName, dbInstance);
}
public InitializingCouchDbConnector(String databaseName, CouchDbInstance dbi, ObjectMapperFactory om) {
public InitializingCouchDbConnector(final String databaseName, final CouchDbInstance dbi, final ObjectMapperFactory om) {
super(databaseName, dbi, om);
}
......@@ -42,14 +42,14 @@ public class InitializingCouchDbConnector extends StdCouchDbConnector implements
final ScriptEngine engine = new ScriptEngineManager().getEngineByMimeType("application/javascript");
engine.eval(new InputStreamReader(new ClassPathResource("couchdb/jsToJson.js").getInputStream()));
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources("classpath:couchdb/*.design.js");
final PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
final Resource[] resources = resolver.getResources("classpath:couchdb/*.design.js");
for (Resource resource : resources) {
logger.debug("Loading CouchDB design doc: {}", resource.getFilename());
String js = FileCopyUtils.copyToString(new InputStreamReader(resource.getInputStream()));
final String js = FileCopyUtils.copyToString(new InputStreamReader(resource.getInputStream()));
/* Reset designDoc before parsing a new one. */
engine.eval("var designDoc = null;" + js);
Bindings jsonObject = (Bindings) engine.eval("jsToJson(designDoc)");
final Bindings jsonObject = (Bindings) engine.eval("jsToJson(designDoc)");
docs.add(jsonObject);
}
}
......@@ -64,10 +64,10 @@ public class InitializingCouchDbConnector extends StdCouchDbConnector implements
}
}
try {
String rev = getCurrentRevision((String) doc.get("_id"));
final String rev = getCurrentRevision((String) doc.get("_id"));
doc.put("_rev", rev);
update(doc);
} catch (DocumentNotFoundException e) {
} catch (final DocumentNotFoundException e) {
create(doc);
}
});
......@@ -80,7 +80,7 @@ public class InitializingCouchDbConnector extends StdCouchDbConnector implements
}
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
public void setResourceLoader(final ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
}
......@@ -38,7 +38,7 @@ public class CommentServiceImpl implements CommentService {
@PreAuthorize("isAuthenticated()")
public boolean saveQuestion(final Comment comment) {
final Session session = sessionRepository.getSessionFromKeyword(comment.getSessionId());
final Comment result = commentRepository.saveQuestion(session, comment, userService.getCurrentUser());
final Comment result = commentRepository.saveQuestion(session.getId(), comment, userService.getCurrentUser());
if (null != result) {
final NewCommentEvent event = new NewCommentEvent(this, session, result);
......@@ -71,9 +71,9 @@ public class CommentServiceImpl implements CommentService {
}
final User user = getCurrentUser();
if (session.isCreator(user)) {
commentRepository.deleteAllInterposedQuestions(session);
commentRepository.deleteAllInterposedQuestions(session.getId());
} else {
commentRepository.deleteAllInterposedQuestions(session, user);
commentRepository.deleteAllInterposedQuestions(session.getId(), user);
}
}
......@@ -91,14 +91,14 @@ public class CommentServiceImpl implements CommentService {
throw new NotFoundException();
}
if (username == null) {
return commentRepository.getInterposedReadingCount(session);
return commentRepository.getInterposedReadingCount(session.getId());
} else {
User currentUser = userService.getCurrentUser();
if (!currentUser.getUsername().equals(username)) {
throw new ForbiddenException();
}
return commentRepository.getInterposedReadingCount(session, currentUser);
return commentRepository.getInterposedReadingCount(session.getId(), currentUser);
}
}
......@@ -108,9 +108,9 @@ public class CommentServiceImpl implements CommentService {
final Session session = this.getSession(sessionKey);
final User user = getCurrentUser();
if (session.isCreator(user)) {
return commentRepository.getInterposedQuestions(session, offset, limit);
return commentRepository.getInterposedQuestions(session.getId(), offset, limit);
} else {
return commentRepository.getInterposedQuestions(session, user, offset, limit);
return commentRepository.getInterposedQuestions(session.getId(), user, offset, limit);
}
}
......
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment