update dependencies, javadoc, formatting

This commit is contained in:
_Bastler 2022-04-13 16:50:35 +02:00
parent 628980db7f
commit d3b2a95472
53 changed files with 636 additions and 728 deletions

View File

@ -10,14 +10,14 @@
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>11</java.version> <java.version>11</java.version>
<log4j2.version>2.16.0</log4j2.version> <log4j2.version>2.17.2</log4j2.version>
<revision>1.3.3</revision> <revision>1.4.0</revision>
</properties> </properties>
<parent> <parent>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId> <artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.5</version> <version>2.6.6</version>
<relativePath /> <relativePath />
</parent> </parent>

View File

@ -13,8 +13,7 @@ import org.hibernate.search.backend.lucene.analysis.LuceneAnalysisConfigurer;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
/** /**
* @author _bastler@bstly.de * The Class LuceneConfig.
*
*/ */
@Configuration @Configuration
public class LuceneConfig implements LuceneAnalysisConfigurer { public class LuceneConfig implements LuceneAnalysisConfigurer {
@ -27,28 +26,22 @@ public class LuceneConfig implements LuceneAnalysisConfigurer {
@Override @Override
public void configure(LuceneAnalysisConfigurationContext context) { public void configure(LuceneAnalysisConfigurationContext context) {
context.analyzer("english").custom().tokenizer(StandardTokenizerFactory.class) context.analyzer("english").custom().tokenizer(StandardTokenizerFactory.class)
.tokenFilter(LowerCaseFilterFactory.class) .tokenFilter(LowerCaseFilterFactory.class).tokenFilter(SnowballPorterFilterFactory.class)
.tokenFilter(SnowballPorterFilterFactory.class).param("language", "English") .param("language", "English").tokenFilter(ASCIIFoldingFilterFactory.class)
.tokenFilter(ASCIIFoldingFilterFactory.class) .tokenFilter(EdgeNGramFilterFactory.class).param("minGramSize", "3").param("maxGramSize", "7");
.tokenFilter(EdgeNGramFilterFactory.class).param("minGramSize", "3")
.param("maxGramSize", "7");
context.analyzer("english_search").custom().tokenizer(StandardTokenizerFactory.class) context.analyzer("english_search").custom().tokenizer(StandardTokenizerFactory.class)
.tokenFilter(LowerCaseFilterFactory.class) .tokenFilter(LowerCaseFilterFactory.class).tokenFilter(SnowballPorterFilterFactory.class)
.tokenFilter(SnowballPorterFilterFactory.class).param("language", "English") .param("language", "English").tokenFilter(ASCIIFoldingFilterFactory.class);
.tokenFilter(ASCIIFoldingFilterFactory.class);
context.analyzer("german").custom().tokenizer(StandardTokenizerFactory.class) context.analyzer("german").custom().tokenizer(StandardTokenizerFactory.class)
.tokenFilter(LowerCaseFilterFactory.class) .tokenFilter(LowerCaseFilterFactory.class).tokenFilter(SnowballPorterFilterFactory.class)
.tokenFilter(SnowballPorterFilterFactory.class).param("language", "German") .param("language", "German").tokenFilter(ASCIIFoldingFilterFactory.class)
.tokenFilter(ASCIIFoldingFilterFactory.class) .tokenFilter(EdgeNGramFilterFactory.class).param("minGramSize", "3").param("maxGramSize", "7");
.tokenFilter(EdgeNGramFilterFactory.class).param("minGramSize", "3")
.param("maxGramSize", "7");
context.analyzer("german_search").custom().tokenizer(StandardTokenizerFactory.class) context.analyzer("german_search").custom().tokenizer(StandardTokenizerFactory.class)
.tokenFilter(LowerCaseFilterFactory.class) .tokenFilter(LowerCaseFilterFactory.class).tokenFilter(SnowballPorterFilterFactory.class)
.tokenFilter(SnowballPorterFilterFactory.class).param("language", "German") .param("language", "German").tokenFilter(ASCIIFoldingFilterFactory.class);
.tokenFilter(ASCIIFoldingFilterFactory.class);
} }

View File

@ -46,24 +46,23 @@ public class BookmarksManager {
* Checks for entry. * Checks for entry.
* *
* @param username the username * @param username the username
* @param entryId the entry id * @param entryId the entry id
* @return true, if successful * @return true, if successful
*/ */
public boolean hasEntry(String username, Long entryId) { public boolean hasEntry(String username, Long entryId) {
return bookmarksRepository.exists(qBookmarks.username.equalsIgnoreCase(username) return bookmarksRepository
.and(qBookmarks.entries.contains(entryId))); .exists(qBookmarks.username.equalsIgnoreCase(username).and(qBookmarks.entries.contains(entryId)));
} }
/** /**
* Adds the entry. * Adds the entry.
* *
* @param username the username * @param username the username
* @param entryId the entry id * @param entryId the entry id
*/ */
public void addEntry(String username, Long entryId) { public void addEntry(String username, Long entryId) {
Assert.isTrue(entryRepository.existsById(entryId), "Invalid entryid"); Assert.isTrue(entryRepository.existsById(entryId), "Invalid entryid");
Assert.isTrue(localUserRepository.exists(qLocalUser.username.equalsIgnoreCase(username)), Assert.isTrue(localUserRepository.exists(qLocalUser.username.equalsIgnoreCase(username)), "Invalid username");
"Invalid username");
Bookmarks bookmarks = get(username); Bookmarks bookmarks = get(username);
if (bookmarks.getEntries() == null) { if (bookmarks.getEntries() == null) {
@ -80,12 +79,11 @@ public class BookmarksManager {
* Removes the entry. * Removes the entry.
* *
* @param username the username * @param username the username
* @param entryId the entry id * @param entryId the entry id
*/ */
public void removeEntry(String username, Long entryId) { public void removeEntry(String username, Long entryId) {
Assert.isTrue(entryRepository.existsById(entryId), "Invalid entryid"); Assert.isTrue(entryRepository.existsById(entryId), "Invalid entryid");
Assert.isTrue(localUserRepository.exists(qLocalUser.username.equalsIgnoreCase(username)), Assert.isTrue(localUserRepository.exists(qLocalUser.username.equalsIgnoreCase(username)), "Invalid username");
"Invalid username");
Bookmarks bookmarks = get(username); Bookmarks bookmarks = get(username);
@ -105,8 +103,7 @@ public class BookmarksManager {
* @param entryId the entry id * @param entryId the entry id
*/ */
public void removeEntry(Long entryId) { public void removeEntry(Long entryId) {
for (Bookmarks bookmarks : bookmarksRepository for (Bookmarks bookmarks : bookmarksRepository.findAll(qBookmarks.entries.contains(entryId))) {
.findAll(qBookmarks.entries.contains(entryId))) {
bookmarks.getEntries().remove(entryId); bookmarks.getEntries().remove(entryId);
bookmarksRepository.save(bookmarks); bookmarksRepository.save(bookmarks);
} }

View File

@ -55,30 +55,29 @@ public class CommentManager {
* Fetch by date. * Fetch by date.
* *
* @param username the username * @param username the username
* @param target the target * @param target the target
* @param parent the parent * @param parent the parent
* @param date the date * @param date the date
* @param page the page * @param page the page
* @param size the size * @param size the size
* @param desc the desc * @param desc the desc
* @return the page * @return the page
*/ */
public Page<Comment> fetchByDate(String username, Long target, Long parent, Instant date, public Page<Comment> fetchByDate(String username, Long target, Long parent, Instant date, int page, int size,
int page, int size, boolean desc) { boolean desc) {
Sort sort = Sort.by(desc ? Order.desc("created") : Order.asc("created")); Sort sort = Sort.by(desc ? Order.desc("created") : Order.asc("created"));
if (parent == null) { if (parent == null) {
return commentRepository return commentRepository.findAll(
.findAll( qComment.target.eq(target).and(qComment.parent.isNull())
qComment.target.eq(target).and(qComment.parent.isNull()) .and(qComment.flaggedStatus.eq(FlaggedStatus.NORMAL))
.and(qComment.flaggedStatus.eq(FlaggedStatus.NORMAL)) .and(qComment.created.before(date).or(qComment.author.eq(username))),
.and(qComment.created.before(date) PageRequest.of(page, size, sort));
.or(qComment.author.eq(username))),
PageRequest.of(page, size, sort));
} }
return commentRepository.findAll(qComment.target.eq(target).and(qComment.parent.eq(parent)) return commentRepository.findAll(
.and(qComment.flaggedStatus.eq(FlaggedStatus.NORMAL)) qComment.target.eq(target).and(qComment.parent.eq(parent))
.and(qComment.created.before(date)), PageRequest.of(page, size, sort)); .and(qComment.flaggedStatus.eq(FlaggedStatus.NORMAL)).and(qComment.created.before(date)),
PageRequest.of(page, size, sort));
} }
/** /**
@ -86,37 +85,37 @@ public class CommentManager {
* *
* @param page the page * @param page the page
* @param size the size * @param size the size
* @param asc the asc * @param asc the asc
* @return the page * @return the page
*/ */
public Page<Comment> fetchFlagged(int page, int size, boolean asc) { public Page<Comment> fetchFlagged(int page, int size, boolean asc) {
Sort sort = Sort.by(asc ? Order.asc("created") : Order.desc("created")); Sort sort = Sort.by(asc ? Order.asc("created") : Order.desc("created"));
JPAQuery<Comment> query = jpaQueryFactory.selectFrom(qComment).leftJoin(qFlag) JPAQuery<Comment> query = jpaQueryFactory.selectFrom(qComment).leftJoin(qFlag).on(qComment.id.eq(qFlag.target))
.on(qComment.id.eq(qFlag.target)).where(qFlag.targetType.eq(Types.comment)) .where(qFlag.targetType.eq(Types.comment)).groupBy(qFlag.target);
.groupBy(qFlag.target);
JPAQuery<Long> countQuery = query.clone().select(qComment.id.countDistinct());
return new PageImpl<Comment>(query return new PageImpl<Comment>(query
.orderBy(new OrderSpecifier<>(asc ? com.querydsl.core.types.Order.ASC .orderBy(new OrderSpecifier<>(
: com.querydsl.core.types.Order.DESC, qComment.created)) asc ? com.querydsl.core.types.Order.ASC : com.querydsl.core.types.Order.DESC, qComment.created))
.limit(size).offset(page * size).fetch(), PageRequest.of(page, size, sort), .limit(size).offset(page * size).fetch(), PageRequest.of(page, size, sort), countQuery.fetchOne());
query.fetchCount());
} }
/** /**
* Fetch by username. * Fetch by username.
* *
* @param username the username * @param username the username
* @param date the date * @param date the date
* @param page the page * @param page the page
* @param size the size * @param size the size
* @param asc the asc * @param asc the asc
* @return the page * @return the page
*/ */
public Page<Comment> fetchByUsername(String username, Instant date, int page, int size, public Page<Comment> fetchByUsername(String username, Instant date, int page, int size, boolean asc) {
boolean asc) {
Sort sort = Sort.by(asc ? Order.asc("created") : Order.desc("created")); Sort sort = Sort.by(asc ? Order.asc("created") : Order.desc("created"));
return commentRepository.findAll(qComment.author.equalsIgnoreCase(username) return commentRepository.findAll(qComment.author.equalsIgnoreCase(username)
.and(qComment.flaggedStatus.eq(FlaggedStatus.NORMAL)) .and(qComment.flaggedStatus.eq(FlaggedStatus.NORMAL)).and(qComment.created.before(date)),
.and(qComment.created.before(date)), PageRequest.of(page, size, sort)); PageRequest.of(page, size, sort));
} }
/** /**
@ -132,8 +131,7 @@ public class CommentManager {
} }
return commentRepository.count(qComment.target.eq(target).and(qComment.parent.eq(parent)) return commentRepository.count(qComment.target.eq(target).and(qComment.parent.eq(parent))
.and(qComment.flaggedStatus.eq(FlaggedStatus.NORMAL)) .and(qComment.flaggedStatus.eq(FlaggedStatus.NORMAL)).and(qComment.created.before(Instant.now())));
.and(qComment.created.before(Instant.now())));
} }
/** /**
@ -143,17 +141,16 @@ public class CommentManager {
* @return the long * @return the long
*/ */
public Long count(Long target) { public Long count(Long target) {
return commentRepository.count( return commentRepository.count(qComment.target.eq(target).and(qComment.flaggedStatus.eq(FlaggedStatus.NORMAL))
qComment.target.eq(target).and(qComment.flaggedStatus.eq(FlaggedStatus.NORMAL)) .and(qComment.created.before(Instant.now())));
.and(qComment.created.before(Instant.now())));
} }
/** /**
* Apply metadata. * Apply metadata.
* *
* @param username the username * @param username the username
* @param comment the comment * @param comment the comment
* @param ignore the ignore * @param ignore the ignore
*/ */
public void applyMetadata(String username, Comment comment, List<String> ignore) { public void applyMetadata(String username, Comment comment, List<String> ignore) {
@ -168,45 +165,36 @@ public class CommentManager {
} }
if (!ignore.contains("points")) { if (!ignore.contains("points")) {
comment.getMetadata().put("points", comment.getMetadata().put("points", voteManager.getPoints(comment.getId(), Types.comment));
voteManager.getPoints(comment.getId(), Types.comment));
} }
if (!ignore.contains("upvoted")) { if (!ignore.contains("upvoted")) {
comment.getMetadata().put("upvoted", comment.getMetadata().put("upvoted",
voteRepository.exists(qVote.target.eq(comment.getId()) voteRepository.exists(qVote.target.eq(comment.getId()).and(qVote.targetType.eq(Types.comment))
.and(qVote.targetType.eq(Types.comment)).and(qVote.type.eq(VoteType.up)) .and(qVote.type.eq(VoteType.up)).and(qVote.author.equalsIgnoreCase(username))));
.and(qVote.author.equalsIgnoreCase(username))));
} }
if (!ignore.contains("downvoted")) { if (!ignore.contains("downvoted")) {
comment.getMetadata().put("downvoted", comment.getMetadata().put("downvoted",
voteRepository.exists( voteRepository.exists(qVote.target.eq(comment.getId()).and(qVote.targetType.eq(Types.comment))
qVote.target.eq(comment.getId()).and(qVote.targetType.eq(Types.comment)) .and(qVote.type.eq(VoteType.down)).and(qVote.author.equalsIgnoreCase(username))));
.and(qVote.type.eq(VoteType.down))
.and(qVote.author.equalsIgnoreCase(username))));
} }
if (!ignore.contains("unvote")) { if (!ignore.contains("unvote")) {
comment.getMetadata().put("unvote", comment.getMetadata().put("unvote", voteRepository.exists(qVote.target.eq(comment.getId())
voteRepository.exists( .and(qVote.targetType.eq(Types.comment)).and(qVote.author.equalsIgnoreCase(username))));
qVote.target.eq(comment.getId()).and(qVote.targetType.eq(Types.comment))
.and(qVote.author.equalsIgnoreCase(username))));
} }
if (!username.equals(comment.getAuthor()) && !ignore.contains("flag")) { if (!username.equals(comment.getAuthor()) && !ignore.contains("flag")) {
comment.getMetadata().put("flag", comment.getMetadata().put("flag", flagManager.get(username, comment.getId(), Types.comment) == null);
flagManager.get(username, comment.getId(), Types.comment) == null);
} }
if (!username.equals(comment.getAuthor()) && !ignore.contains("unflag")) { if (!username.equals(comment.getAuthor()) && !ignore.contains("unflag")) {
comment.getMetadata().put("unflag", comment.getMetadata().put("unflag", flagManager.get(username, comment.getId(), Types.comment) != null);
flagManager.get(username, comment.getId(), Types.comment) != null);
} }
if (!ignore.contains("flagged")) { if (!ignore.contains("flagged")) {
comment.getMetadata().put("flagged", comment.getMetadata().put("flagged", flagManager.getFlags(comment.getId(), Types.comment) > 0);
flagManager.getFlags(comment.getId(), Types.comment) > 0);
} }
if (!ignore.contains("entry")) { if (!ignore.contains("entry")) {
@ -219,8 +207,8 @@ public class CommentManager {
* Apply metadata. * Apply metadata.
* *
* @param username the username * @param username the username
* @param entries the entries * @param entries the entries
* @param ignore the ignore * @param ignore the ignore
*/ */
public void applyMetadata(String username, List<Comment> entries, List<String> ignore) { public void applyMetadata(String username, List<Comment> entries, List<String> ignore) {
for (Comment comment : entries) { for (Comment comment : entries) {
@ -265,10 +253,10 @@ public class CommentManager {
* @return the points * @return the points
*/ */
public long getPoints(Long commentId) { public long getPoints(Long commentId) {
long upvotes = voteRepository.count(qVote.targetType.eq(Types.comment) long upvotes = voteRepository.count(
.and(qVote.type.eq(VoteType.up)).and(qVote.target.eq(commentId))); qVote.targetType.eq(Types.comment).and(qVote.type.eq(VoteType.up)).and(qVote.target.eq(commentId)));
long downvotes = voteRepository.count(qVote.targetType.eq(Types.comment) long downvotes = voteRepository.count(
.and(qVote.type.eq(VoteType.down)).and(qVote.target.eq(commentId))); qVote.targetType.eq(Types.comment).and(qVote.type.eq(VoteType.down)).and(qVote.target.eq(commentId)));
return upvotes - downvotes; return upvotes - downvotes;
} }

View File

@ -74,9 +74,7 @@ public class EntryManager {
static final String COMMENTS_QUERY = "SELECT DISTINCT comment.target,MAX(comment.created) as last,COUNT(comment.id) AS count FROM comments as comment WHERE comment.flagged_status = :flag GROUP BY comment.target"; static final String COMMENTS_QUERY = "SELECT DISTINCT comment.target,MAX(comment.created) as last,COUNT(comment.id) AS count FROM comments as comment WHERE comment.flagged_status = :flag GROUP BY comment.target";
static final String RANK_CALCULATION_QUERY = "SELECT DISTINCT entry.*, (IFNULL(upvote.count,0) - IFNULL(downvote.count,0)) as points, (IFNULL(upvote.count,0) - IFNULL(downvote.count,0)) / IF(:gravity > 0, POW(TIMESTAMPDIFF(HOUR, entry.created, :before)+2,:gravity), 1) AS ranking FROM entries AS entry LEFT JOIN (" static final String RANK_CALCULATION_QUERY = "SELECT DISTINCT entry.*, (IFNULL(upvote.count,0) - IFNULL(downvote.count,0)) as points, (IFNULL(upvote.count,0) - IFNULL(downvote.count,0)) / IF(:gravity > 0, POW(TIMESTAMPDIFF(HOUR, entry.created, :before)+2,:gravity), 1) AS ranking FROM entries AS entry LEFT JOIN ("
+ UPVOTES_QUERY + UPVOTES_QUERY + ") AS upvote ON upvote.target = entry.id LEFT JOIN (" + DOWNVOTES_QUERY
+ ") AS upvote ON upvote.target = entry.id LEFT JOIN ("
+ DOWNVOTES_QUERY
+ ") AS downvote ON downvote.target = entry.id %s"; + ") AS downvote ON downvote.target = entry.id %s";
static final String DATE_QUERY = "SELECT DISTINCT entry.* FROM entries AS entry %s"; static final String DATE_QUERY = "SELECT DISTINCT entry.* FROM entries AS entry %s";
@ -84,12 +82,10 @@ public class EntryManager {
static final String USER_QUERY = "SELECT DISTINCT entry.* FROM entries AS entry %s ORDER BY entry.created :order"; static final String USER_QUERY = "SELECT DISTINCT entry.* FROM entries AS entry %s ORDER BY entry.created :order";
static final String COMMENT_CALCULATION_QUERY = "SELECT DISTINCT entry.*, IFNULL(comment.count,0) as comments, IFNULL(comment.count,0) / IF(:gravity > 0, POW(TIMESTAMPDIFF(HOUR, comment.last, :before)+2,:gravity), 1) AS ranking FROM entries AS entry LEFT JOIN (" static final String COMMENT_CALCULATION_QUERY = "SELECT DISTINCT entry.*, IFNULL(comment.count,0) as comments, IFNULL(comment.count,0) / IF(:gravity > 0, POW(TIMESTAMPDIFF(HOUR, comment.last, :before)+2,:gravity), 1) AS ranking FROM entries AS entry LEFT JOIN ("
+ COMMENTS_QUERY + COMMENTS_QUERY + ") AS comment ON comment.target = entry.id %s";
+ ") AS comment ON comment.target = entry.id %s";
static final String LAST_COMMENT_QUERY = "SELECT DISTINCT entry.* FROM entries AS entry LEFT JOIN (" static final String LAST_COMMENT_QUERY = "SELECT DISTINCT entry.* FROM entries AS entry LEFT JOIN ("
+ COMMENTS_QUERY + COMMENTS_QUERY + ") AS comment ON comment.target = entry.id %s ";
+ ") AS comment ON comment.target = entry.id %s ";
static final String COUNT_QUERY = "SELECT count(entry.id) FROM entries as entry %s"; static final String COUNT_QUERY = "SELECT count(entry.id) FROM entries as entry %s";
@ -97,15 +93,15 @@ public class EntryManager {
* Fetch by ranking. * Fetch by ranking.
* *
* @param username the username * @param username the username
* @param filter the filter * @param filter the filter
* @param gravity the gravity * @param gravity the gravity
* @param page the page * @param page the page
* @param size the size * @param size the size
* @param asc the asc * @param asc the asc
* @return the page * @return the page
*/ */
public Page<Entry> fetchByRanking(String username, EntryFilter filter, float gravity, int page, public Page<Entry> fetchByRanking(String username, EntryFilter filter, float gravity, int page, int size,
int size, boolean asc) { boolean asc) {
Query query = createEntryQuery(RANK_CALCULATION_QUERY, username, filter, Query query = createEntryQuery(RANK_CALCULATION_QUERY, username, filter,
asc ? "ranking ASC, entry.created ASC" : "ranking DESC, entry.created DESC"); asc ? "ranking ASC, entry.created ASC" : "ranking DESC, entry.created DESC");
query.setParameter("gravity", gravity); query.setParameter("gravity", gravity);
@ -122,16 +118,14 @@ public class EntryManager {
* Fetch by date. * Fetch by date.
* *
* @param username the username * @param username the username
* @param filter the filter * @param filter the filter
* @param page the page * @param page the page
* @param size the size * @param size the size
* @param asc the asc * @param asc the asc
* @return the page * @return the page
*/ */
public Page<Entry> fetchByDate(String username, EntryFilter filter, int page, int size, public Page<Entry> fetchByDate(String username, EntryFilter filter, int page, int size, boolean asc) {
boolean asc) { Query query = createEntryQuery(DATE_QUERY, username, filter, asc ? "entry.created ASC" : "entry.created DESC");
Query query = createEntryQuery(DATE_QUERY, username, filter,
asc ? "entry.created ASC" : "entry.created DESC");
query.setFirstResult((page) * size); query.setFirstResult((page) * size);
query.setMaxResults(size); query.setMaxResults(size);
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -145,15 +139,15 @@ public class EntryManager {
* Fetch by comments. * Fetch by comments.
* *
* @param username the username * @param username the username
* @param filter the filter * @param filter the filter
* @param gravity the gravity * @param gravity the gravity
* @param page the page * @param page the page
* @param size the size * @param size the size
* @param asc the asc * @param asc the asc
* @return the page * @return the page
*/ */
public Page<Entry> fetchByComments(String username, EntryFilter filter, float gravity, public Page<Entry> fetchByComments(String username, EntryFilter filter, float gravity, int page, int size,
int page, int size, boolean asc) { boolean asc) {
Query query = createEntryQuery(COMMENT_CALCULATION_QUERY, username, filter, Query query = createEntryQuery(COMMENT_CALCULATION_QUERY, username, filter,
asc ? "ranking ASC, entry.created ASC" : "ranking DESC, entry.created DESC"); asc ? "ranking ASC, entry.created ASC" : "ranking DESC, entry.created DESC");
query.setParameter("gravity", gravity); query.setParameter("gravity", gravity);
@ -170,17 +164,15 @@ public class EntryManager {
* Fetch by last comment. * Fetch by last comment.
* *
* @param username the username * @param username the username
* @param filter the filter * @param filter the filter
* @param page the page * @param page the page
* @param size the size * @param size the size
* @param asc the asc * @param asc the asc
* @return the page * @return the page
*/ */
public Page<Entry> fetchByLastComment(String username, EntryFilter filter, int page, int size, public Page<Entry> fetchByLastComment(String username, EntryFilter filter, int page, int size, boolean asc) {
boolean asc) {
Query query = createEntryQuery(LAST_COMMENT_QUERY, username, filter, Query query = createEntryQuery(LAST_COMMENT_QUERY, username, filter,
asc ? "comment.last ASC, entry.created ASC" asc ? "comment.last ASC, entry.created ASC" : "comment.last DESC, entry.created DESC");
: "comment.last DESC, entry.created DESC");
query.setFirstResult((page) * size); query.setFirstResult((page) * size);
query.setMaxResults(size); query.setMaxResults(size);
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -195,17 +187,16 @@ public class EntryManager {
* *
* @param fromUser the from user * @param fromUser the from user
* @param username the username * @param username the username
* @param filter the filter * @param filter the filter
* @param page the page * @param page the page
* @param size the size * @param size the size
* @param asc the asc * @param asc the asc
* @return the page * @return the page
*/ */
public Page<Entry> fetchByUser(String fromUser, String username, EntryFilter filter, int page, public Page<Entry> fetchByUser(String fromUser, String username, EntryFilter filter, int page, int size,
int size, boolean asc) { boolean asc) {
filter.setAdditional("AND entry.author = :username"); filter.setAdditional("AND entry.author = :username");
Query query = createEntryQuery(DATE_QUERY, username, filter, Query query = createEntryQuery(DATE_QUERY, username, filter, asc ? "entry.created ASC" : "entry.created DESC");
asc ? "entry.created ASC" : "entry.created DESC");
query.setParameter("username", username); query.setParameter("username", username);
query.setFirstResult((page) * size); query.setFirstResult((page) * size);
query.setMaxResults(size); query.setMaxResults(size);
@ -222,20 +213,17 @@ public class EntryManager {
* *
* @param rawQuery the raw query * @param rawQuery the raw query
* @param username the username * @param username the username
* @param filter the filter * @param filter the filter
* @param orderBy the order by * @param orderBy the order by
* @return the query * @return the query
*/ */
protected Query createEntryQuery(String rawQuery, String username, EntryFilter filter, protected Query createEntryQuery(String rawQuery, String username, EntryFilter filter, String orderBy) {
String orderBy) {
String filterString = ""; String filterString = "";
String tagsString = ""; String tagsString = "";
if (filter.getTags() != null && !filter.getTags().isEmpty()) { if (filter.getTags() != null && !filter.getTags().isEmpty()) {
for (int index = 0; index < filter.getTags().size(); index++) { for (int index = 0; index < filter.getTags().size(); index++) {
tagsString += "'" tagsString += "'" + filter.getTags().get(index) + "'";
+ filter.getTags().get(index)
+ "'";
if (index < filter.getTags().size() - 1) { if (index < filter.getTags().size() - 1) {
tagsString += ","; tagsString += ",";
} }
@ -243,17 +231,13 @@ public class EntryManager {
} }
if (StringUtils.hasText(tagsString)) { if (StringUtils.hasText(tagsString)) {
filterString += " INNER JOIN tags as tag ON entry.id = tag.target AND tag.tag IN (" filterString += " INNER JOIN tags as tag ON entry.id = tag.target AND tag.tag IN (" + tagsString + ")";
+ tagsString
+ ")";
} }
String fixedTagsString = ""; String fixedTagsString = "";
if (filter.getFixedTags() != null && !filter.getFixedTags().isEmpty()) { if (filter.getFixedTags() != null && !filter.getFixedTags().isEmpty()) {
for (int index = 0; index < filter.getFixedTags().size(); index++) { for (int index = 0; index < filter.getFixedTags().size(); index++) {
fixedTagsString += "'" fixedTagsString += "'" + filter.getFixedTags().get(index) + "'";
+ filter.getFixedTags().get(index)
+ "'";
if (index < filter.getFixedTags().size() - 1) { if (index < filter.getFixedTags().size() - 1) {
fixedTagsString += ","; fixedTagsString += ",";
} }
@ -262,8 +246,7 @@ public class EntryManager {
if (StringUtils.hasText(fixedTagsString)) { if (StringUtils.hasText(fixedTagsString)) {
filterString += " INNER JOIN tags as fixedTag ON entry.id = fixedTag.target AND fixedTag.tag IN (" filterString += " INNER JOIN tags as fixedTag ON entry.id = fixedTag.target AND fixedTag.tag IN ("
+ fixedTagsString + fixedTagsString + ")";
+ ")";
} }
boolean author = false; boolean author = false;
@ -286,16 +269,13 @@ public class EntryManager {
} }
if (StringUtils.hasText(filter.getAdditional())) { if (StringUtils.hasText(filter.getAdditional())) {
filterString += " " filterString += " " + filter.getAdditional();
+ filter.getAdditional();
} }
String excludedTagsString = ""; String excludedTagsString = "";
if (filter.getExcludedTags() != null && !filter.getExcludedTags().isEmpty()) { if (filter.getExcludedTags() != null && !filter.getExcludedTags().isEmpty()) {
for (int index = 0; index < filter.getExcludedTags().size(); index++) { for (int index = 0; index < filter.getExcludedTags().size(); index++) {
excludedTagsString += "'" excludedTagsString += "'" + filter.getExcludedTags().get(index) + "'";
+ filter.getExcludedTags().get(index)
+ "'";
if (index < filter.getExcludedTags().size() - 1) { if (index < filter.getExcludedTags().size() - 1) {
excludedTagsString += ","; excludedTagsString += ",";
} }
@ -304,16 +284,13 @@ public class EntryManager {
if (StringUtils.hasText(excludedTagsString)) { if (StringUtils.hasText(excludedTagsString)) {
filterString += " AND NOT EXISTS (SELECT * FROM tags as excludedTag WHERE entry.id = excludedTag.target AND excludedTag.tag IN (" filterString += " AND NOT EXISTS (SELECT * FROM tags as excludedTag WHERE entry.id = excludedTag.target AND excludedTag.tag IN ("
+ excludedTagsString + excludedTagsString + "))";
+ "))";
} }
String fixedExcludedTagsString = ""; String fixedExcludedTagsString = "";
if (filter.getFixedExcludedTags() != null && !filter.getFixedExcludedTags().isEmpty()) { if (filter.getFixedExcludedTags() != null && !filter.getFixedExcludedTags().isEmpty()) {
for (int index = 0; index < filter.getFixedExcludedTags().size(); index++) { for (int index = 0; index < filter.getFixedExcludedTags().size(); index++) {
fixedExcludedTagsString += "'" fixedExcludedTagsString += "'" + filter.getFixedExcludedTags().get(index) + "'";
+ filter.getFixedExcludedTags().get(index)
+ "'";
if (index < filter.getFixedExcludedTags().size() - 1) { if (index < filter.getFixedExcludedTags().size() - 1) {
fixedExcludedTagsString += ","; fixedExcludedTagsString += ",";
} }
@ -322,13 +299,11 @@ public class EntryManager {
if (StringUtils.hasText(fixedExcludedTagsString)) { if (StringUtils.hasText(fixedExcludedTagsString)) {
filterString += " AND NOT EXISTS (SELECT * FROM tags as fixedExcludedTag WHERE entry.id = fixedExcludedTag.target AND fixedExcludedTag.tag IN (" filterString += " AND NOT EXISTS (SELECT * FROM tags as fixedExcludedTag WHERE entry.id = fixedExcludedTag.target AND fixedExcludedTag.tag IN ("
+ fixedExcludedTagsString + fixedExcludedTagsString + "))";
+ "))";
} }
if (StringUtils.hasText(orderBy)) { if (StringUtils.hasText(orderBy)) {
filterString += " ORDER BY " filterString += " ORDER BY " + orderBy;
+ orderBy;
} }
Query query = em.createNativeQuery(String.format(rawQuery, filterString), Entry.class); Query query = em.createNativeQuery(String.format(rawQuery, filterString), Entry.class);
@ -351,7 +326,7 @@ public class EntryManager {
* *
* @param rawQuery the raw query * @param rawQuery the raw query
* @param username the username * @param username the username
* @param filter the filter * @param filter the filter
* @return the query * @return the query
*/ */
protected Query createCountQuery(String rawQuery, String username, EntryFilter filter) { protected Query createCountQuery(String rawQuery, String username, EntryFilter filter) {
@ -360,9 +335,7 @@ public class EntryManager {
String tagsString = ""; String tagsString = "";
if (filter.getTags() != null && !filter.getTags().isEmpty()) { if (filter.getTags() != null && !filter.getTags().isEmpty()) {
for (int index = 0; index < filter.getTags().size(); index++) { for (int index = 0; index < filter.getTags().size(); index++) {
tagsString += "'" tagsString += "'" + filter.getTags().get(index) + "'";
+ filter.getTags().get(index)
+ "'";
if (index < filter.getTags().size() - 1) { if (index < filter.getTags().size() - 1) {
tagsString += ","; tagsString += ",";
} }
@ -370,9 +343,7 @@ public class EntryManager {
} }
if (StringUtils.hasText(tagsString)) { if (StringUtils.hasText(tagsString)) {
filterString += " INNER JOIN tags as tag ON entry.id = tag.target AND tag.tag IN (" filterString += " INNER JOIN tags as tag ON entry.id = tag.target AND tag.tag IN (" + tagsString + ")";
+ tagsString
+ ")";
} }
boolean author = false; boolean author = false;
@ -395,16 +366,13 @@ public class EntryManager {
} }
if (StringUtils.hasText(filter.getAdditional())) { if (StringUtils.hasText(filter.getAdditional())) {
filterString += " " filterString += " " + filter.getAdditional();
+ filter.getAdditional();
} }
String excludedTagsString = ""; String excludedTagsString = "";
if (filter.getExcludedTags() != null && !filter.getExcludedTags().isEmpty()) { if (filter.getExcludedTags() != null && !filter.getExcludedTags().isEmpty()) {
for (int index = 0; index < filter.getExcludedTags().size(); index++) { for (int index = 0; index < filter.getExcludedTags().size(); index++) {
excludedTagsString += "'" excludedTagsString += "'" + filter.getExcludedTags().get(index) + "'";
+ filter.getExcludedTags().get(index)
+ "'";
if (index < filter.getExcludedTags().size() - 1) { if (index < filter.getExcludedTags().size() - 1) {
excludedTagsString += ","; excludedTagsString += ",";
} }
@ -413,8 +381,7 @@ public class EntryManager {
if (StringUtils.hasText(excludedTagsString)) { if (StringUtils.hasText(excludedTagsString)) {
filterString += " AND NOT EXISTS (SELECT * FROM tags as excludedTag WHERE entry.id = excludedTag.target AND excludedTag.tag IN (" filterString += " AND NOT EXISTS (SELECT * FROM tags as excludedTag WHERE entry.id = excludedTag.target AND excludedTag.tag IN ("
+ excludedTagsString + excludedTagsString + "))";
+ "))";
} }
Query query = em.createNativeQuery(String.format(rawQuery, filterString)); Query query = em.createNativeQuery(String.format(rawQuery, filterString));
@ -437,27 +404,28 @@ public class EntryManager {
* *
* @param page the page * @param page the page
* @param size the size * @param size the size
* @param asc the asc * @param asc the asc
* @return the page * @return the page
*/ */
public Page<Entry> fetchFlagged(int page, int size, boolean asc) { public Page<Entry> fetchFlagged(int page, int size, boolean asc) {
Sort sort = Sort.by(asc ? Order.asc("created") : Order.desc("created")); Sort sort = Sort.by(asc ? Order.asc("created") : Order.desc("created"));
JPAQuery<Entry> query = jpaQueryFactory.selectFrom(qEntry).leftJoin(qFlag) JPAQuery<Entry> query = jpaQueryFactory.selectFrom(qEntry).leftJoin(qFlag).on(qEntry.id.eq(qFlag.target))
.on(qEntry.id.eq(qFlag.target)).where(qFlag.targetType.eq(Types.entry)) .where(qFlag.targetType.eq(Types.entry)).groupBy(qFlag.target);
.groupBy(qFlag.target);
JPAQuery<Long> countQuery = query.clone().select(qEntry.id.countDistinct());
return new PageImpl<Entry>(query return new PageImpl<Entry>(query
.orderBy(new OrderSpecifier<>(asc ? com.querydsl.core.types.Order.ASC .orderBy(new OrderSpecifier<>(
: com.querydsl.core.types.Order.DESC, qEntry.created)) asc ? com.querydsl.core.types.Order.ASC : com.querydsl.core.types.Order.DESC, qEntry.created))
.limit(size).offset(page * size).fetch(), PageRequest.of(page, size, sort), .limit(size).offset(page * size).fetch(), PageRequest.of(page, size, sort), countQuery.fetchOne());
query.fetchCount());
} }
/** /**
* Fetch by bookmarks. * Fetch by bookmarks.
* *
* @param username the username * @param username the username
* @param page the page * @param page the page
* @param size the size * @param size the size
* @return the page * @return the page
*/ */
public Page<Entry> fetchByBookmarks(String username, int page, int size) { public Page<Entry> fetchByBookmarks(String username, int page, int size) {
@ -475,9 +443,9 @@ public class EntryManager {
* Apply metadata. * Apply metadata.
* *
* @param username the username * @param username the username
* @param karma the karma * @param karma the karma
* @param entry the entry * @param entry the entry
* @param ignore the ignore * @param ignore the ignore
*/ */
public void applyMetadata(String username, long karma, Entry entry, List<String> ignore) { public void applyMetadata(String username, long karma, Entry entry, List<String> ignore) {
@ -490,8 +458,8 @@ public class EntryManager {
} }
if (!ignore.contains("edit")) { if (!ignore.contains("edit")) {
entry.getMetadata().put("edit", entry.getAuthor().equals(username) entry.getMetadata().put("edit",
&& entry.getCreated().isAfter(Instant.now())); entry.getAuthor().equals(username) && entry.getCreated().isAfter(Instant.now()));
} }
if (!ignore.contains("comments")) { if (!ignore.contains("comments")) {
@ -503,47 +471,39 @@ public class EntryManager {
} }
if (!ignore.contains("bookmark")) { if (!ignore.contains("bookmark")) {
entry.getMetadata().put("bookmark", entry.getMetadata().put("bookmark", !bookmarksManager.hasEntry(username, entry.getId()));
!bookmarksManager.hasEntry(username, entry.getId()));
} }
if (!ignore.contains("removeBookmark")) { if (!ignore.contains("removeBookmark")) {
entry.getMetadata().put("removeBookmark", entry.getMetadata().put("removeBookmark", bookmarksManager.hasEntry(username, entry.getId()));
bookmarksManager.hasEntry(username, entry.getId()));
} }
if (!ignore.contains("upvoted")) { if (!ignore.contains("upvoted")) {
entry.getMetadata().put("upvoted", entry.getMetadata().put("upvoted",
voteRepository.exists(qVote.target.eq(entry.getId()) voteRepository.exists(qVote.target.eq(entry.getId()).and(qVote.targetType.eq(Types.entry))
.and(qVote.targetType.eq(Types.entry)).and(qVote.type.eq(VoteType.up)) .and(qVote.type.eq(VoteType.up)).and(qVote.author.equalsIgnoreCase(username))));
.and(qVote.author.equalsIgnoreCase(username))));
} }
if (!ignore.contains("downvoted")) { if (!ignore.contains("downvoted")) {
entry.getMetadata().put("downvoted", entry.getMetadata().put("downvoted",
voteRepository.exists(qVote.target.eq(entry.getId()) voteRepository.exists(qVote.target.eq(entry.getId()).and(qVote.targetType.eq(Types.entry))
.and(qVote.targetType.eq(Types.entry)).and(qVote.type.eq(VoteType.down)) .and(qVote.type.eq(VoteType.down)).and(qVote.author.equalsIgnoreCase(username))));
.and(qVote.author.equalsIgnoreCase(username))));
} }
if (!username.equals(entry.getAuthor()) && !ignore.contains("flag")) { if (!username.equals(entry.getAuthor()) && !ignore.contains("flag")) {
entry.getMetadata().put("flag", entry.getMetadata().put("flag", flagManager.get(username, entry.getId(), Types.entry) == null);
flagManager.get(username, entry.getId(), Types.entry) == null);
} }
if (!username.equals(entry.getAuthor()) && !ignore.contains("unflag")) { if (!username.equals(entry.getAuthor()) && !ignore.contains("unflag")) {
entry.getMetadata().put("unflag", entry.getMetadata().put("unflag", flagManager.get(username, entry.getId(), Types.entry) != null);
flagManager.get(username, entry.getId(), Types.entry) != null);
} }
if (!ignore.contains("flagged")) { if (!ignore.contains("flagged")) {
entry.getMetadata().put("flagged", entry.getMetadata().put("flagged", flagManager.getFlags(entry.getId(), Types.entry) > 0);
flagManager.getFlags(entry.getId(), Types.entry) > 0);
} }
if (voteRepository if (voteRepository.exists(qVote.target.eq(entry.getId()).and(qVote.targetType.eq(Types.entry))
.exists(qVote.target.eq(entry.getId()).and(qVote.targetType.eq(Types.entry)) .and(qVote.author.equalsIgnoreCase(username)))) {
.and(qVote.author.equalsIgnoreCase(username)))) {
if (!ignore.contains("unvote")) { if (!ignore.contains("unvote")) {
entry.getMetadata().put("unvote", true); entry.getMetadata().put("unvote", true);
} }
@ -562,12 +522,11 @@ public class EntryManager {
* Apply metadata. * Apply metadata.
* *
* @param username the username * @param username the username
* @param karma the karma * @param karma the karma
* @param entries the entries * @param entries the entries
* @param ignore the ignore * @param ignore the ignore
*/ */
public void applyMetadata(String username, long karma, List<Entry> entries, public void applyMetadata(String username, long karma, List<Entry> entries, List<String> ignore) {
List<String> ignore) {
for (Entry entry : entries) { for (Entry entry : entries) {
applyMetadata(username, karma, entry, ignore); applyMetadata(username, karma, entry, ignore);
} }
@ -635,17 +594,17 @@ public class EntryManager {
* @return the points * @return the points
*/ */
public long getPoints(Long entryId) { public long getPoints(Long entryId) {
long upvotes = voteRepository.count(qVote.targetType.eq(Types.entry) long upvotes = voteRepository
.and(qVote.type.eq(VoteType.up)).and(qVote.target.eq(entryId))); .count(qVote.targetType.eq(Types.entry).and(qVote.type.eq(VoteType.up)).and(qVote.target.eq(entryId)));
long downvotes = voteRepository.count(qVote.targetType.eq(Types.entry) long downvotes = voteRepository.count(
.and(qVote.type.eq(VoteType.down)).and(qVote.target.eq(entryId))); qVote.targetType.eq(Types.entry).and(qVote.type.eq(VoteType.down)).and(qVote.target.eq(entryId)));
return upvotes - downvotes; return upvotes - downvotes;
} }
/** /**
* Gets the user points. * Gets the user points.
* *
* @param entryId the entry id * @param entryId the entry id
* @param username the username * @param username the username
* @return the user points * @return the user points
*/ */

View File

@ -40,14 +40,15 @@ public class FlagManager {
/** /**
* Gets the. * Gets the.
* *
* @param author the author * @param author the author
* @param target the target * @param target the target
* @param targetType the target type * @param targetType the target type
* @return the flag * @return the flag
*/ */
public Flag get(String author, Long target, Types targetType) { public Flag get(String author, Long target, Types targetType) {
return flagRepository.findOne(qFlag.author.eq(author).and(qFlag.targetType.eq(targetType)) return flagRepository
.and(qFlag.target.eq(target))).orElse(null); .findOne(qFlag.author.eq(author).and(qFlag.targetType.eq(targetType)).and(qFlag.target.eq(target)))
.orElse(null);
} }
/** /**
@ -72,12 +73,11 @@ public class FlagManager {
/** /**
* Delete by target. * Delete by target.
* *
* @param target the target * @param target the target
* @param targetType the target type * @param targetType the target type
*/ */
public void deleteByTarget(Long target, Types targetType) { public void deleteByTarget(Long target, Types targetType) {
for (Flag flag : flagRepository for (Flag flag : flagRepository.findAll(qFlag.target.eq(target).and(qFlag.targetType.eq(targetType)))) {
.findAll(qFlag.target.eq(target).and(qFlag.targetType.eq(targetType)))) {
delete(flag); delete(flag);
} }
} }
@ -85,7 +85,7 @@ public class FlagManager {
/** /**
* Gets the flags. * Gets the flags.
* *
* @param target the target * @param target the target
* @param targetType the target type * @param targetType the target type
* @return the flags * @return the flags
*/ */
@ -96,7 +96,7 @@ public class FlagManager {
/** /**
* Check flag status. * Check flag status.
* *
* @param target the target * @param target the target
* @param targetType the target type * @param targetType the target type
*/ */
public void checkFlagStatus(Long target, Types targetType) { public void checkFlagStatus(Long target, Types targetType) {
@ -120,9 +120,7 @@ public class FlagManager {
* @param target the target * @param target the target
*/ */
public void checkCommentFlagStatus(Long target) { public void checkCommentFlagStatus(Long target) {
Assert.isTrue(commentManager.exists(target), "Comment not exists: '" Assert.isTrue(commentManager.exists(target), "Comment not exists: '" + target + "'!");
+ target
+ "'!");
Comment comment = commentManager.get(target); Comment comment = commentManager.get(target);
if (getFlags(target, Types.comment) >= settingsManager.getFlahThresh()) { if (getFlags(target, Types.comment) >= settingsManager.getFlahThresh()) {
@ -151,8 +149,8 @@ public class FlagManager {
* @param comment the comment * @param comment the comment
*/ */
protected void hideSubcomments(Comment comment) { protected void hideSubcomments(Comment comment) {
for (Comment subcomment : commentRepository.findAll(qComment.parent.eq(comment.getId()) for (Comment subcomment : commentRepository
.and(qComment.flaggedStatus.eq(FlaggedStatus.NORMAL)))) { .findAll(qComment.parent.eq(comment.getId()).and(qComment.flaggedStatus.eq(FlaggedStatus.NORMAL)))) {
subcomment.setFlaggedStatus(FlaggedStatus.HIDDEN); subcomment.setFlaggedStatus(FlaggedStatus.HIDDEN);
subcomment = commentManager.save(subcomment); subcomment = commentManager.save(subcomment);
hideSubcomments(subcomment); hideSubcomments(subcomment);
@ -176,8 +174,8 @@ public class FlagManager {
* @param comment the comment * @param comment the comment
*/ */
protected void unhideSubcomments(Comment comment) { protected void unhideSubcomments(Comment comment) {
for (Comment subcomment : commentRepository.findAll(qComment.parent.eq(comment.getId()) for (Comment subcomment : commentRepository
.and(qComment.flaggedStatus.eq(FlaggedStatus.HIDDEN)))) { .findAll(qComment.parent.eq(comment.getId()).and(qComment.flaggedStatus.eq(FlaggedStatus.HIDDEN)))) {
subcomment.setFlaggedStatus(FlaggedStatus.NORMAL); subcomment.setFlaggedStatus(FlaggedStatus.NORMAL);
subcomment = commentManager.save(subcomment); subcomment = commentManager.save(subcomment);
hideSubcomments(subcomment); hideSubcomments(subcomment);
@ -190,9 +188,7 @@ public class FlagManager {
* @param target the target * @param target the target
*/ */
public void checkEntryFlagStatus(Long target) { public void checkEntryFlagStatus(Long target) {
Assert.isTrue(entryManager.exists(target), "Entry not exists: '" Assert.isTrue(entryManager.exists(target), "Entry not exists: '" + target + "'!");
+ target
+ "'!");
Entry entry = entryManager.get(target); Entry entry = entryManager.get(target);
if (getFlags(target, Types.entry) >= settingsManager.getFlahThresh()) { if (getFlags(target, Types.entry) >= settingsManager.getFlahThresh()) {
if (!FlaggedStatus.FLAGGED.equals(entry.getFlaggedStatus())) { if (!FlaggedStatus.FLAGGED.equals(entry.getFlaggedStatus())) {
@ -208,7 +204,7 @@ public class FlagManager {
/** /**
* Unflag. * Unflag.
* *
* @param target the target * @param target the target
* @param targetType the target type * @param targetType the target type
*/ */
public void unflag(Long target, Types targetType) { public void unflag(Long target, Types targetType) {

View File

@ -20,7 +20,7 @@ public class InstantHelper {
* Plus. * Plus.
* *
* @param instant the instant * @param instant the instant
* @param amount the amount * @param amount the amount
* @return the instant * @return the instant
*/ */
public static Instant plus(Instant instant, TemporalAmount amount) { public static Instant plus(Instant instant, TemporalAmount amount) {
@ -30,9 +30,9 @@ public class InstantHelper {
/** /**
* Plus. * Plus.
* *
* @param instant the instant * @param instant the instant
* @param amountToAdd the amount to add * @param amountToAdd the amount to add
* @param unit the unit * @param unit the unit
* @return the instant * @return the instant
*/ */
public static Instant plus(Instant instant, long amountToAdd, TemporalUnit unit) { public static Instant plus(Instant instant, long amountToAdd, TemporalUnit unit) {
@ -43,7 +43,7 @@ public class InstantHelper {
* Minus. * Minus.
* *
* @param instant the instant * @param instant the instant
* @param amount the amount * @param amount the amount
* @return the instant * @return the instant
*/ */
public static Instant minus(Instant instant, TemporalAmount amount) { public static Instant minus(Instant instant, TemporalAmount amount) {
@ -53,32 +53,29 @@ public class InstantHelper {
/** /**
* Minus. * Minus.
* *
* @param instant the instant * @param instant the instant
* @param amountToAdd the amount to add * @param amountToAdd the amount to add
* @param unit the unit * @param unit the unit
* @return the instant * @return the instant
*/ */
public static Instant minus(Instant instant, long amountToAdd, TemporalUnit unit) { public static Instant minus(Instant instant, long amountToAdd, TemporalUnit unit) {
return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC).minus(amountToAdd, unit) return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC).minus(amountToAdd, unit).toInstant();
.toInstant();
} }
/** /**
* Truncate. * Truncate.
* *
* @param instant the instant * @param instant the instant
* @param unit the unit * @param unit the unit
* @return the instant * @return the instant
*/ */
public static Instant truncate(Instant instant, TemporalUnit unit) { public static Instant truncate(Instant instant, TemporalUnit unit) {
if (ChronoUnit.YEARS.equals(unit)) { if (ChronoUnit.YEARS.equals(unit)) {
instant = instant.truncatedTo(ChronoUnit.DAYS); instant = instant.truncatedTo(ChronoUnit.DAYS);
return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC) return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC).with(ChronoField.DAY_OF_YEAR, 1L).toInstant();
.with(ChronoField.DAY_OF_YEAR, 1L).toInstant();
} else if (ChronoUnit.MONTHS.equals(unit)) { } else if (ChronoUnit.MONTHS.equals(unit)) {
instant = instant.truncatedTo(ChronoUnit.DAYS); instant = instant.truncatedTo(ChronoUnit.DAYS);
return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC) return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC).with(ChronoField.DAY_OF_MONTH, 1L).toInstant();
.with(ChronoField.DAY_OF_MONTH, 1L).toInstant();
} }
return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC).truncatedTo(unit).toInstant(); return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC).truncatedTo(unit).toInstant();

View File

@ -61,8 +61,8 @@ public class SearchManager implements SmartInitializingSingleton {
@EventListener(ContextRefreshedEvent.class) @EventListener(ContextRefreshedEvent.class)
@Transactional @Transactional
public void onApplicationEvent(ContextRefreshedEvent event) { public void onApplicationEvent(ContextRefreshedEvent event) {
MassIndexer indexer = searchSession.massIndexer().idFetchSize(150) MassIndexer indexer = searchSession.massIndexer().idFetchSize(150).batchSizeToLoadObjects(25)
.batchSizeToLoadObjects(25).threadsToLoadObjects(12); .threadsToLoadObjects(12);
try { try {
logger.info("start indexing!"); logger.info("start indexing!");
indexer.startAndWait(); indexer.startAndWait();
@ -73,9 +73,20 @@ public class SearchManager implements SmartInitializingSingleton {
} }
} }
/**
* Search.
*
* @param types the types
* @param search the search
* @param page the page
* @param size the size
* @param asc the asc
* @param sortByDate the sort by date
* @return the search result
*/
@Transactional @Transactional
public SearchResult<Object> search(List<Types> types, String search, int page, int size, public SearchResult<Object> search(List<Types> types, String search, int page, int size, boolean asc,
boolean asc, boolean sortByDate) { boolean sortByDate) {
List<Class<? extends Object>> classes = Lists.newArrayList(); List<Class<? extends Object>> classes = Lists.newArrayList();
for (Types type : types) { for (Types type : types) {
switch (type) { switch (type) {
@ -91,26 +102,20 @@ public class SearchManager implements SmartInitializingSingleton {
} }
if (classes.contains(Entry.class)) { if (classes.contains(Entry.class)) {
return searchSession.search(classes) return searchSession.search(classes).where(f -> f.bool()
.where(f -> f.bool() .should(f.match().field("title").matching(search).boost(settingsManager.getGravity()))
.should(f.match().field("title").matching(search) .should(f.match().field("title_de").matching(search).boost(settingsManager.getGravity()))
.boost(settingsManager.getGravity())) .should(f.match().field("url").matching(search)).should(f.match().field("url_de").matching(search))
.should(f.match().field("title_de").matching(search) .should(f.match().field("text").matching(search))
.boost(settingsManager.getGravity())) .should(f.match().field("text_de").matching(search)))
.should(f.match().field("url").matching(search)) .sort(f -> sortByDate ? (asc ? f.field("created").asc() : f.field("created").desc())
.should(f.match().field("url_de").matching(search))
.should(f.match().field("text").matching(search))
.should(f.match().field("text_de").matching(search)))
.sort(f -> sortByDate
? (asc ? f.field("created").asc() : f.field("created").desc())
: (asc ? f.score().asc() : f.score().desc())) : (asc ? f.score().asc() : f.score().desc()))
.fetch(page * size, size); .fetch(page * size, size);
} else { } else {
return searchSession.search(classes) return searchSession.search(classes)
.where(f -> f.bool().should(f.match().field("text").matching(search)) .where(f -> f.bool().should(f.match().field("text").matching(search))
.should(f.match().field("text_de").matching(search))) .should(f.match().field("text_de").matching(search)))
.sort(f -> sortByDate .sort(f -> sortByDate ? (asc ? f.field("created").asc() : f.field("created").desc())
? (asc ? f.field("created").asc() : f.field("created").desc())
: (asc ? f.score().asc() : f.score().desc())) : (asc ? f.score().asc() : f.score().desc()))
.fetch(page * size, size); .fetch(page * size, size);
} }

View File

@ -93,9 +93,9 @@ public class SettingsManager {
} }
/** /**
* Gets the max user pages. * Gets the max views.
* *
* @return the max user pages * @return the max views
*/ */
public long getMaxViews() { public long getMaxViews() {
return MAX_VIEWS; return MAX_VIEWS;

View File

@ -29,7 +29,7 @@ public class TagManager {
/** /**
* Creates the. * Creates the.
* *
* @param tag the tag * @param tag the tag
* @param target the target * @param target the target
* @return the tag * @return the tag
*/ */
@ -40,7 +40,7 @@ public class TagManager {
/** /**
* Delete. * Delete.
* *
* @param tag the tag * @param tag the tag
* @param target the target * @param target the target
*/ */
public void delete(String tag, Long target) { public void delete(String tag, Long target) {
@ -54,15 +54,14 @@ public class TagManager {
* @return the for target * @return the for target
*/ */
public List<String> getForTarget(Long target) { public List<String> getForTarget(Long target) {
return jpaQueryFactory.selectFrom(qTag).where(qTag.target.eq(target)).select(qTag.tag) return jpaQueryFactory.selectFrom(qTag).where(qTag.target.eq(target)).select(qTag.tag).fetch();
.fetch();
} }
/** /**
* Sets the for target. * Sets the for target.
* *
* @param target the target * @param target the target
* @param tags the tags * @param tags the tags
*/ */
public void setForTarget(Long target, List<String> tags) { public void setForTarget(Long target, List<String> tags) {
deleteByTarget(target); deleteByTarget(target);
@ -89,8 +88,8 @@ public class TagManager {
* @return the list * @return the list
*/ */
public List<String> search(String search) { public List<String> search(String search) {
return jpaQueryFactory.selectFrom(qTag).where(qTag.tag.containsIgnoreCase(search)) return jpaQueryFactory.selectFrom(qTag).where(qTag.tag.containsIgnoreCase(search)).distinct().limit(10)
.distinct().limit(10).select(qTag.tag).fetch(); .select(qTag.tag).fetch();
} }
} }

View File

@ -60,88 +60,116 @@ public class UserManager implements UserDetailsService, SmartInitializingSinglet
* loadUserByUsername(java.lang.String) * loadUserByUsername(java.lang.String)
*/ */
/* /*
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String) * @see org.springframework.security.core.userdetails.UserDetailsService#
* loadUserByUsername(java.lang.String)
*/ */
/* /*
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String) * @see org.springframework.security.core.userdetails.UserDetailsService#
* loadUserByUsername(java.lang.String)
*/ */
/* /*
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String) * @see org.springframework.security.core.userdetails.UserDetailsService#
* loadUserByUsername(java.lang.String)
*/ */
/* /*
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String) * @see org.springframework.security.core.userdetails.UserDetailsService#
* loadUserByUsername(java.lang.String)
*/ */
/* /*
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String) * @see org.springframework.security.core.userdetails.UserDetailsService#
* loadUserByUsername(java.lang.String)
*/ */
/* /*
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String) * @see org.springframework.security.core.userdetails.UserDetailsService#
* loadUserByUsername(java.lang.String)
*/ */
/* /*
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String) * @see org.springframework.security.core.userdetails.UserDetailsService#
* loadUserByUsername(java.lang.String)
*/ */
/* /*
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String) * @see org.springframework.security.core.userdetails.UserDetailsService#
* loadUserByUsername(java.lang.String)
*/ */
/* /*
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String) * @see org.springframework.security.core.userdetails.UserDetailsService#
* loadUserByUsername(java.lang.String)
*/ */
/* /*
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String) * @see org.springframework.security.core.userdetails.UserDetailsService#
* loadUserByUsername(java.lang.String)
*/ */
/* /*
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String) * @see org.springframework.security.core.userdetails.UserDetailsService#
* loadUserByUsername(java.lang.String)
*/ */
/* /*
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String) * @see org.springframework.security.core.userdetails.UserDetailsService#
* loadUserByUsername(java.lang.String)
*/ */
/* /*
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String) * @see org.springframework.security.core.userdetails.UserDetailsService#
* loadUserByUsername(java.lang.String)
*/ */
/* /*
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String) * @see org.springframework.security.core.userdetails.UserDetailsService#
* loadUserByUsername(java.lang.String)
*/ */
/* /*
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String) * @see org.springframework.security.core.userdetails.UserDetailsService#
* loadUserByUsername(java.lang.String)
*/ */
/* /*
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String) * @see org.springframework.security.core.userdetails.UserDetailsService#
* loadUserByUsername(java.lang.String)
*/ */
/* /*
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String) * @see org.springframework.security.core.userdetails.UserDetailsService#
* loadUserByUsername(java.lang.String)
*/ */
/* /*
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String) * @see org.springframework.security.core.userdetails.UserDetailsService#
* loadUserByUsername(java.lang.String)
*/ */
/* /*
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String) * @see org.springframework.security.core.userdetails.UserDetailsService#
* loadUserByUsername(java.lang.String)
*/ */
/* /*
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String) * @see org.springframework.security.core.userdetails.UserDetailsService#
* loadUserByUsername(java.lang.String)
*/ */
/* /*
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String) * @see org.springframework.security.core.userdetails.UserDetailsService#
* loadUserByUsername(java.lang.String)
*/ */
/* /*
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String) * @see org.springframework.security.core.userdetails.UserDetailsService#
* loadUserByUsername(java.lang.String)
*/ */
/* /*
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String) * @see org.springframework.security.core.userdetails.UserDetailsService#
* loadUserByUsername(java.lang.String)
*/ */
/* /*
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String) * @see org.springframework.security.core.userdetails.UserDetailsService#
* loadUserByUsername(java.lang.String)
*/ */
/* /*
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String) * @see org.springframework.security.core.userdetails.UserDetailsService#
* loadUserByUsername(java.lang.String)
*/ */
/* /*
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String) * @see org.springframework.security.core.userdetails.UserDetailsService#
* loadUserByUsername(java.lang.String)
*/ */
/* /*
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String) * @see org.springframework.security.core.userdetails.UserDetailsService#
* loadUserByUsername(java.lang.String)
*/ */
/* /*
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String) * @see org.springframework.security.core.userdetails.UserDetailsService#
* loadUserByUsername(java.lang.String)
*/ */
/* /*
* @see org.springframework.security.core.userdetails.UserDetailsService# * @see org.springframework.security.core.userdetails.UserDetailsService#
@ -177,88 +205,116 @@ public class UserManager implements UserDetailsService, SmartInitializingSinglet
* afterSingletonsInstantiated() * afterSingletonsInstantiated()
*/ */
/* /*
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated() * @see org.springframework.beans.factory.SmartInitializingSingleton#
* afterSingletonsInstantiated()
*/ */
/* /*
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated() * @see org.springframework.beans.factory.SmartInitializingSingleton#
* afterSingletonsInstantiated()
*/ */
/* /*
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated() * @see org.springframework.beans.factory.SmartInitializingSingleton#
* afterSingletonsInstantiated()
*/ */
/* /*
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated() * @see org.springframework.beans.factory.SmartInitializingSingleton#
* afterSingletonsInstantiated()
*/ */
/* /*
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated() * @see org.springframework.beans.factory.SmartInitializingSingleton#
* afterSingletonsInstantiated()
*/ */
/* /*
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated() * @see org.springframework.beans.factory.SmartInitializingSingleton#
* afterSingletonsInstantiated()
*/ */
/* /*
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated() * @see org.springframework.beans.factory.SmartInitializingSingleton#
* afterSingletonsInstantiated()
*/ */
/* /*
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated() * @see org.springframework.beans.factory.SmartInitializingSingleton#
* afterSingletonsInstantiated()
*/ */
/* /*
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated() * @see org.springframework.beans.factory.SmartInitializingSingleton#
* afterSingletonsInstantiated()
*/ */
/* /*
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated() * @see org.springframework.beans.factory.SmartInitializingSingleton#
* afterSingletonsInstantiated()
*/ */
/* /*
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated() * @see org.springframework.beans.factory.SmartInitializingSingleton#
* afterSingletonsInstantiated()
*/ */
/* /*
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated() * @see org.springframework.beans.factory.SmartInitializingSingleton#
* afterSingletonsInstantiated()
*/ */
/* /*
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated() * @see org.springframework.beans.factory.SmartInitializingSingleton#
* afterSingletonsInstantiated()
*/ */
/* /*
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated() * @see org.springframework.beans.factory.SmartInitializingSingleton#
* afterSingletonsInstantiated()
*/ */
/* /*
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated() * @see org.springframework.beans.factory.SmartInitializingSingleton#
* afterSingletonsInstantiated()
*/ */
/* /*
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated() * @see org.springframework.beans.factory.SmartInitializingSingleton#
* afterSingletonsInstantiated()
*/ */
/* /*
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated() * @see org.springframework.beans.factory.SmartInitializingSingleton#
* afterSingletonsInstantiated()
*/ */
/* /*
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated() * @see org.springframework.beans.factory.SmartInitializingSingleton#
* afterSingletonsInstantiated()
*/ */
/* /*
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated() * @see org.springframework.beans.factory.SmartInitializingSingleton#
* afterSingletonsInstantiated()
*/ */
/* /*
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated() * @see org.springframework.beans.factory.SmartInitializingSingleton#
* afterSingletonsInstantiated()
*/ */
/* /*
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated() * @see org.springframework.beans.factory.SmartInitializingSingleton#
* afterSingletonsInstantiated()
*/ */
/* /*
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated() * @see org.springframework.beans.factory.SmartInitializingSingleton#
* afterSingletonsInstantiated()
*/ */
/* /*
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated() * @see org.springframework.beans.factory.SmartInitializingSingleton#
* afterSingletonsInstantiated()
*/ */
/* /*
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated() * @see org.springframework.beans.factory.SmartInitializingSingleton#
* afterSingletonsInstantiated()
*/ */
/* /*
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated() * @see org.springframework.beans.factory.SmartInitializingSingleton#
* afterSingletonsInstantiated()
*/ */
/* /*
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated() * @see org.springframework.beans.factory.SmartInitializingSingleton#
* afterSingletonsInstantiated()
*/ */
/* /*
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated() * @see org.springframework.beans.factory.SmartInitializingSingleton#
* afterSingletonsInstantiated()
*/ */
/* /*
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated() * @see org.springframework.beans.factory.SmartInitializingSingleton#
* afterSingletonsInstantiated()
*/ */
/* /*
* @see org.springframework.beans.factory.SmartInitializingSingleton# * @see org.springframework.beans.factory.SmartInitializingSingleton#
@ -269,8 +325,7 @@ public class UserManager implements UserDetailsService, SmartInitializingSinglet
if (!localUserRepository.exists(qLocalUser.roles.contains("ROLE_ADMIN"))) { if (!localUserRepository.exists(qLocalUser.roles.contains("ROLE_ADMIN"))) {
if (!StringUtils.hasText(adminPassword)) { if (!StringUtils.hasText(adminPassword)) {
adminPassword = RandomStringUtils.random(24, true, true); adminPassword = RandomStringUtils.random(24, true, true);
logger.error("password for 'admin': " logger.error("password for 'admin': " + adminPassword);
+ adminPassword);
} }
LocalUser admin = new LocalUser(); LocalUser admin = new LocalUser();
admin.setUsername("admin"); admin.setUsername("admin");
@ -288,8 +343,7 @@ public class UserManager implements UserDetailsService, SmartInitializingSinglet
* @return the by username * @return the by username
*/ */
public LocalUser getByUsername(String username) { public LocalUser getByUsername(String username) {
return localUserRepository.findOne(qLocalUser.username.equalsIgnoreCase(username)) return localUserRepository.findOne(qLocalUser.username.equalsIgnoreCase(username)).orElse(null);
.orElse(null);
} }
/** /**
@ -315,9 +369,7 @@ public class UserManager implements UserDetailsService, SmartInitializingSinglet
return getByUsername(token.getName()); return getByUsername(token.getName());
} else if (authentication instanceof OAuth2AuthenticationToken) { } else if (authentication instanceof OAuth2AuthenticationToken) {
OAuth2AuthenticationToken token = (OAuth2AuthenticationToken) authentication; OAuth2AuthenticationToken token = (OAuth2AuthenticationToken) authentication;
String externalId = token.getAuthorizedClientRegistrationId() String externalId = token.getAuthorizedClientRegistrationId() + "-" + token.getName();
+ "-"
+ token.getName();
LocalUser localUser = getByExternalId(externalId); LocalUser localUser = getByExternalId(externalId);
if (localUser == null) { if (localUser == null) {
localUser = new LocalUser(); localUser = new LocalUser();
@ -334,11 +386,8 @@ public class UserManager implements UserDetailsService, SmartInitializingSinglet
} }
int count = 1; int count = 1;
String username = tmpUsername; String username = tmpUsername;
while (localUserRepository while (localUserRepository.exists(qLocalUser.username.equalsIgnoreCase(username))) {
.exists(qLocalUser.username.equalsIgnoreCase(username))) { username = tmpUsername + "-" + count;
username = tmpUsername
+ "-"
+ count;
count++; count++;
} }
@ -369,11 +418,10 @@ public class UserManager implements UserDetailsService, SmartInitializingSinglet
* Apply metadata. * Apply metadata.
* *
* @param username the username * @param username the username
* @param user the user * @param user the user
*/ */
public void applyMetadata(String username, LocalUser user) { public void applyMetadata(String username, LocalUser user) {
if (user.getUsername().equalsIgnoreCase(username) if (user.getUsername().equalsIgnoreCase(username) && !user.getMetadata().containsKey("self")) {
&& !user.getMetadata().containsKey("self")) {
user.getMetadata().put("self", true); user.getMetadata().put("self", true);
} }

View File

@ -35,15 +35,14 @@ public class ViewManager {
* @return true, if successful * @return true, if successful
*/ */
public boolean exists(String username, String name) { public boolean exists(String username, String name) {
return viewRepository return viewRepository.exists(qView.username.equalsIgnoreCase(username).and(qView.name.eq(name)));
.exists(qView.username.equalsIgnoreCase(username).and(qView.name.eq(name)));
} }
/** /**
* Gets the. * Gets the.
* *
* @param id the id * @param id the id
* @return the user page * @return the view
*/ */
public View get(Long id) { public View get(Long id) {
return viewRepository.findById(id).orElse(null); return viewRepository.findById(id).orElse(null);
@ -54,19 +53,17 @@ public class ViewManager {
* *
* @param username the username * @param username the username
* @param name the name * @param name the name
* @return the user page * @return the view
*/ */
public View get(String username, String name) { public View get(String username, String name) {
return viewRepository return viewRepository.findOne(qView.username.equalsIgnoreCase(username).and(qView.name.eq(name))).orElse(null);
.findOne(qView.username.equalsIgnoreCase(username).and(qView.name.eq(name)))
.orElse(null);
} }
/** /**
* Save. * Save.
* *
* @param view the user page * @param view the view
* @return the user page * @return the view
*/ */
public View save(View view) { public View save(View view) {
return viewRepository.save(view); return viewRepository.save(view);
@ -78,7 +75,6 @@ public class ViewManager {
* @param username the username * @param username the username
* @param page the page * @param page the page
* @param size the size * @param size the size
* @param sortBy the sort by
* @param desc the desc * @param desc the desc
* @return the by user * @return the by user
*/ */
@ -109,8 +105,7 @@ public class ViewManager {
* @return the public * @return the public
*/ */
public Page<View> getPublic(String username, int page, int size, String sortBy, boolean desc) { public Page<View> getPublic(String username, int page, int size, String sortBy, boolean desc) {
return viewRepository.findAll( return viewRepository.findAll(qView.username.notEqualsIgnoreCase(username).and(qView.publicView.isTrue()),
qView.username.notEqualsIgnoreCase(username).and(qView.publicView.isTrue()),
PageRequest.of(page, size, Sort.by(desc ? Direction.DESC : Direction.ASC, sortBy))); PageRequest.of(page, size, Sort.by(desc ? Direction.DESC : Direction.ASC, sortBy)));
} }
@ -125,6 +120,11 @@ public class ViewManager {
viewRepository.delete(get(username, name)); viewRepository.delete(get(username, name));
} }
/**
* Creates the default.
*
* @param username the username
*/
public void createDefault(String username) { public void createDefault(String username) {
if (!exists(username, "TOP")) { if (!exists(username, "TOP")) {
View viewTop = new View(); View viewTop = new View();

View File

@ -26,14 +26,15 @@ public class VoteManager {
/** /**
* Gets the. * Gets the.
* *
* @param author the author * @param author the author
* @param target the target * @param target the target
* @param targetType the target type * @param targetType the target type
* @return the vote * @return the vote
*/ */
public Vote get(String author, Long target, Types targetType) { public Vote get(String author, Long target, Types targetType) {
return voteRepository.findOne(qVote.author.eq(author).and(qVote.targetType.eq(targetType)) return voteRepository
.and(qVote.target.eq(target))).orElse(null); .findOne(qVote.author.eq(author).and(qVote.targetType.eq(targetType)).and(qVote.target.eq(target)))
.orElse(null);
} }
/** /**
@ -58,12 +59,11 @@ public class VoteManager {
/** /**
* Delete by target. * Delete by target.
* *
* @param target the target * @param target the target
* @param targetType the target type * @param targetType the target type
*/ */
public void deleteByTarget(Long target, Types targetType) { public void deleteByTarget(Long target, Types targetType) {
for (Vote vote : voteRepository for (Vote vote : voteRepository.findAll(qVote.target.eq(target).and(qVote.targetType.eq(targetType)))) {
.findAll(qVote.target.eq(target).and(qVote.targetType.eq(targetType)))) {
delete(vote); delete(vote);
} }
} }
@ -71,16 +71,15 @@ public class VoteManager {
/** /**
* Gets the points. * Gets the points.
* *
* @param target the target * @param target the target
* @param targetType the target type * @param targetType the target type
* @return the points * @return the points
*/ */
public Long getPoints(Long target, Types targetType) { public Long getPoints(Long target, Types targetType) {
return voteRepository return voteRepository
.count(qVote.target.eq(target) .count(qVote.target.eq(target).and(qVote.targetType.eq(targetType).and(qVote.type.eq(VoteType.up))))
.and(qVote.targetType.eq(targetType).and(qVote.type.eq(VoteType.up)))) - voteRepository.count(
- voteRepository.count(qVote.target.eq(target) qVote.target.eq(target).and(qVote.targetType.eq(targetType).and(qVote.type.eq(VoteType.down))));
.and(qVote.targetType.eq(targetType).and(qVote.type.eq(VoteType.down))));
} }
} }

View File

@ -11,7 +11,6 @@ import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAmount; import java.time.temporal.TemporalAmount;
import java.time.temporal.TemporalUnit; import java.time.temporal.TemporalUnit;
/** /**
* The Class InstantHelper. * The Class InstantHelper.
*/ */
@ -21,7 +20,7 @@ public class InstantHelper {
* Plus. * Plus.
* *
* @param instant the instant * @param instant the instant
* @param amount the amount * @param amount the amount
* @return the instant * @return the instant
*/ */
public static Instant plus(Instant instant, TemporalAmount amount) { public static Instant plus(Instant instant, TemporalAmount amount) {
@ -31,9 +30,9 @@ public class InstantHelper {
/** /**
* Plus. * Plus.
* *
* @param instant the instant * @param instant the instant
* @param amountToAdd the amount to add * @param amountToAdd the amount to add
* @param unit the unit * @param unit the unit
* @return the instant * @return the instant
*/ */
public static Instant plus(Instant instant, long amountToAdd, TemporalUnit unit) { public static Instant plus(Instant instant, long amountToAdd, TemporalUnit unit) {
@ -44,7 +43,7 @@ public class InstantHelper {
* Minus. * Minus.
* *
* @param instant the instant * @param instant the instant
* @param amount the amount * @param amount the amount
* @return the instant * @return the instant
*/ */
public static Instant minus(Instant instant, TemporalAmount amount) { public static Instant minus(Instant instant, TemporalAmount amount) {
@ -54,32 +53,29 @@ public class InstantHelper {
/** /**
* Minus. * Minus.
* *
* @param instant the instant * @param instant the instant
* @param amountToAdd the amount to add * @param amountToAdd the amount to add
* @param unit the unit * @param unit the unit
* @return the instant * @return the instant
*/ */
public static Instant minus(Instant instant, long amountToAdd, TemporalUnit unit) { public static Instant minus(Instant instant, long amountToAdd, TemporalUnit unit) {
return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC).minus(amountToAdd, unit) return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC).minus(amountToAdd, unit).toInstant();
.toInstant();
} }
/** /**
* Truncate. * Truncate.
* *
* @param instant the instant * @param instant the instant
* @param unit the unit * @param unit the unit
* @return the instant * @return the instant
*/ */
public static Instant truncate(Instant instant, TemporalUnit unit) { public static Instant truncate(Instant instant, TemporalUnit unit) {
if (ChronoUnit.YEARS.equals(unit)) { if (ChronoUnit.YEARS.equals(unit)) {
instant = instant.truncatedTo(ChronoUnit.DAYS); instant = instant.truncatedTo(ChronoUnit.DAYS);
return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC) return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC).with(ChronoField.DAY_OF_YEAR, 1L).toInstant();
.with(ChronoField.DAY_OF_YEAR, 1L).toInstant();
} else if (ChronoUnit.MONTHS.equals(unit)) { } else if (ChronoUnit.MONTHS.equals(unit)) {
instant = instant.truncatedTo(ChronoUnit.DAYS); instant = instant.truncatedTo(ChronoUnit.DAYS);
return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC) return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC).with(ChronoField.DAY_OF_MONTH, 1L).toInstant();
.with(ChronoField.DAY_OF_MONTH, 1L).toInstant();
} }
return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC).truncatedTo(unit).toInstant(); return ZonedDateTime.ofInstant(instant, ZoneOffset.UTC).truncatedTo(unit).toInstant();

View File

@ -58,18 +58,13 @@ public class AuthenticationController extends BaseController {
public List<Client> getExternalLoginUrls() { public List<Client> getExternalLoginUrls() {
List<Client> clients = Lists.newArrayList(); List<Client> clients = Lists.newArrayList();
Iterable<ClientRegistration> clientRegistrations = null; Iterable<ClientRegistration> clientRegistrations = null;
ResolvableType type = ResolvableType.forInstance(clientRegistrationRepository) ResolvableType type = ResolvableType.forInstance(clientRegistrationRepository).as(Iterable.class);
.as(Iterable.class); if (type != ResolvableType.NONE && ClientRegistration.class.isAssignableFrom(type.resolveGenerics()[0])) {
if (type != ResolvableType.NONE
&& ClientRegistration.class.isAssignableFrom(type.resolveGenerics()[0])) {
clientRegistrations = (Iterable<ClientRegistration>) clientRegistrationRepository; clientRegistrations = (Iterable<ClientRegistration>) clientRegistrationRepository;
} }
clientRegistrations clientRegistrations.forEach(registration -> clients.add(new Client(registration.getRegistrationId(),
.forEach(registration -> clients.add(new Client(registration.getRegistrationId(), authorizationRequestBaseUri + "/" + registration.getRegistrationId())));
authorizationRequestBaseUri
+ "/"
+ registration.getRegistrationId())));
return clients; return clients;
} }
@ -86,7 +81,7 @@ public class AuthenticationController extends BaseController {
/** /**
* Instantiates a new client. * Instantiates a new client.
* *
* @param id the id * @param id the id
* @param loginUrl the login url * @param loginUrl the login url
*/ */
public Client(String id, String loginUrl) { public Client(String id, String loginUrl) {

View File

@ -63,8 +63,7 @@ public class BaseController {
String username = getCurrentUsername(); String username = getCurrentUsername();
if (username != null) { if (username != null) {
LocalUser localUser = userManager.getByUsername(username); LocalUser localUser = userManager.getByUsername(username);
if (localUser.getSettings() != null if (localUser.getSettings() != null && localUser.getSettings().containsKey("pageSize")) {
&& localUser.getSettings().containsKey("pageSize")) {
try { try {
return Integer.parseInt(localUser.getSettings().get("pageSize")); return Integer.parseInt(localUser.getSettings().get("pageSize"));
} catch (Exception e) { } catch (Exception e) {
@ -112,8 +111,7 @@ public class BaseController {
String username = getCurrentUsername(); String username = getCurrentUsername();
if (username != null) { if (username != null) {
LocalUser localUser = userManager.getByUsername(username); LocalUser localUser = userManager.getByUsername(username);
if (localUser.getSettings() != null if (localUser.getSettings() != null && localUser.getSettings().containsKey("entryDelay")) {
&& localUser.getSettings().containsKey("entryDelay")) {
try { try {
long entryDelay = Long.parseLong(localUser.getSettings().get("entryDelay")); long entryDelay = Long.parseLong(localUser.getSettings().get("entryDelay"));
@ -142,8 +140,7 @@ public class BaseController {
String username = getCurrentUsername(); String username = getCurrentUsername();
if (username != null) { if (username != null) {
LocalUser localUser = userManager.getByUsername(username); LocalUser localUser = userManager.getByUsername(username);
if (localUser.getSettings() != null if (localUser.getSettings() != null && localUser.getSettings().containsKey("commentDelay")) {
&& localUser.getSettings().containsKey("commentDelay")) {
try { try {
long commentDelay = Long.parseLong(localUser.getSettings().get("commentDelay")); long commentDelay = Long.parseLong(localUser.getSettings().get("commentDelay"));

View File

@ -46,8 +46,8 @@ public class BookmarksController extends BaseController {
/** /**
* Gets the entries. * Gets the entries.
* *
* @param pageParameter the page parameter * @param pageParameter the page parameter
* @param sizeParameter the size parameter * @param sizeParameter the size parameter
* @param ignoreParameter the ignore parameter * @param ignoreParameter the ignore parameter
* @return the entries * @return the entries
*/ */
@ -61,8 +61,8 @@ public class BookmarksController extends BaseController {
sizeParameter = Optional.of(100); sizeParameter = Optional.of(100);
} }
Page<Entry> entries = entryManager.fetchByBookmarks(getCurrentUsername(), Page<Entry> entries = entryManager.fetchByBookmarks(getCurrentUsername(), pageParameter.orElse(0),
pageParameter.orElse(0), sizeParameter.orElse(settingsManager.getPageSize())); sizeParameter.orElse(settingsManager.getPageSize()));
List<String> ignore = ignoreParameter.orElse(Lists.newArrayList()); List<String> ignore = ignoreParameter.orElse(Lists.newArrayList());
entryManager.applyMetadata(getCurrentUsername(), userManager.getKarma(getCurrentUsername()), entryManager.applyMetadata(getCurrentUsername(), userManager.getKarma(getCurrentUsername()),

View File

@ -66,8 +66,7 @@ public class CommentController extends BaseController {
*/ */
@PreAuthorize("isAuthenticated()") @PreAuthorize("isAuthenticated()")
@GetMapping({ "/new/{target}", "/new/{target}/{parent}" }) @GetMapping({ "/new/{target}", "/new/{target}/{parent}" })
public Page<Comment> fetchByDate(@PathVariable("target") Long target, public Page<Comment> fetchByDate(@PathVariable("target") Long target, @PathVariable("parent") Optional<Long> parent,
@PathVariable("parent") Optional<Long> parent,
@RequestParam("page") Optional<Integer> pageParameter, @RequestParam("page") Optional<Integer> pageParameter,
@RequestParam("size") Optional<Integer> sizeParameter, @RequestParam("size") Optional<Integer> sizeParameter,
@RequestParam("date") Optional<Instant> dateParameter, @RequestParam("date") Optional<Instant> dateParameter,
@ -81,8 +80,8 @@ public class CommentController extends BaseController {
if (dateParameter.isPresent() && dateParameter.get().isAfter(Instant.now())) { if (dateParameter.isPresent() && dateParameter.get().isAfter(Instant.now())) {
dateParameter = Optional.of(Instant.now()); dateParameter = Optional.of(Instant.now());
} }
Page<Comment> comments = commentManager.fetchByDate(getCurrentUsername(), target, Page<Comment> comments = commentManager.fetchByDate(getCurrentUsername(), target, parent.orElse(null),
parent.orElse(null), dateParameter.orElse(Instant.now()), pageParameter.orElse(0), dateParameter.orElse(Instant.now()), pageParameter.orElse(0),
sizeParameter.orElse(settingsManager.getPageSize()), descParameter.orElse(false)); sizeParameter.orElse(settingsManager.getPageSize()), descParameter.orElse(false));
List<String> ignore = ignoreParameter.orElse(Lists.newArrayList("entry")); List<String> ignore = ignoreParameter.orElse(Lists.newArrayList("entry"));
@ -106,8 +105,7 @@ public class CommentController extends BaseController {
public Page<Comment> fetchByUsername(@PathVariable("username") String username, public Page<Comment> fetchByUsername(@PathVariable("username") String username,
@RequestParam("page") Optional<Integer> pageParameter, @RequestParam("page") Optional<Integer> pageParameter,
@RequestParam("size") Optional<Integer> sizeParameter, @RequestParam("size") Optional<Integer> sizeParameter,
@RequestParam("date") Optional<Instant> dateParameter, @RequestParam("date") Optional<Instant> dateParameter, @RequestParam("asc") Optional<Boolean> ascParameter,
@RequestParam("asc") Optional<Boolean> ascParameter,
@RequestParam("ignore") Optional<List<String>> ignoreParameter) { @RequestParam("ignore") Optional<List<String>> ignoreParameter) {
if (sizeParameter.isPresent() && sizeParameter.get() > 100) { if (sizeParameter.isPresent() && sizeParameter.get() > 100) {
@ -118,9 +116,9 @@ public class CommentController extends BaseController {
dateParameter = Optional.of(Instant.now()); dateParameter = Optional.of(Instant.now());
} }
Page<Comment> comments = commentManager.fetchByUsername(username, Page<Comment> comments = commentManager.fetchByUsername(username, dateParameter.orElse(Instant.now()),
dateParameter.orElse(Instant.now()), pageParameter.orElse(0), pageParameter.orElse(0), sizeParameter.orElse(settingsManager.getPageSize()),
sizeParameter.orElse(settingsManager.getPageSize()), ascParameter.orElse(false)); ascParameter.orElse(false));
List<String> ignore = ignoreParameter.orElse(Lists.newArrayList()); List<String> ignore = ignoreParameter.orElse(Lists.newArrayList());
commentManager.applyMetadata(getCurrentUsername(), comments.getContent(), ignore); commentManager.applyMetadata(getCurrentUsername(), comments.getContent(), ignore);
return comments; return comments;
@ -135,8 +133,7 @@ public class CommentController extends BaseController {
*/ */
@PreAuthorize("isAuthenticated()") @PreAuthorize("isAuthenticated()")
@GetMapping({ "/count/{target}", "/count/{target}/{parent}" }) @GetMapping({ "/count/{target}", "/count/{target}/{parent}" })
public Long countComments(@PathVariable("target") Long target, public Long countComments(@PathVariable("target") Long target, @PathVariable("parent") Optional<Long> parent) {
@PathVariable("parent") Optional<Long> parent) {
return commentManager.count(target, parent.orElse(null)); return commentManager.count(target, parent.orElse(null));
} }
@ -177,8 +174,7 @@ public class CommentController extends BaseController {
commentValidator.validate(comment, bindingResult); commentValidator.validate(comment, bindingResult);
if (bindingResult.hasErrors()) { if (bindingResult.hasErrors()) {
throw new EntityResponseStatusException(bindingResult.getAllErrors(), throw new EntityResponseStatusException(bindingResult.getAllErrors(), HttpStatus.UNPROCESSABLE_ENTITY);
HttpStatus.UNPROCESSABLE_ENTITY);
} }
comment.setCreated(Instant.now().plus(getCommentDelay(), ChronoUnit.MINUTES)); comment.setCreated(Instant.now().plus(getCommentDelay(), ChronoUnit.MINUTES));
@ -221,8 +217,7 @@ public class CommentController extends BaseController {
commentValidator.validate(comment, bindingResult); commentValidator.validate(comment, bindingResult);
if (bindingResult.hasErrors()) { if (bindingResult.hasErrors()) {
throw new EntityResponseStatusException(bindingResult.getAllErrors(), throw new EntityResponseStatusException(bindingResult.getAllErrors(), HttpStatus.UNPROCESSABLE_ENTITY);
HttpStatus.UNPROCESSABLE_ENTITY);
} }
orgComment.setText(comment.getText()); orgComment.setText(comment.getText());

View File

@ -38,7 +38,7 @@ import de.bstly.board.repository.VoteRepository;
@RestController @RestController
@RequestMapping("/debug") @RequestMapping("/debug")
public class DebugController extends BaseController { public class DebugController extends BaseController {
private Logger logger = LoggerFactory.getLogger(DebugController.class); private Logger logger = LoggerFactory.getLogger(DebugController.class);
@Autowired @Autowired
@ -103,28 +103,21 @@ public class DebugController extends BaseController {
public void random() { public void random() {
logger.warn("start random generation"); logger.warn("start random generation");
long userCount = localUserRepository long userCount = localUserRepository.count(QLocalUser.localUser.username.startsWith("user"));
.count(QLocalUser.localUser.username.startsWith("user"));
for (long i = userCount; i < userCount + users; i++) { for (long i = userCount; i < userCount + users; i++) {
LocalUser localUser = new LocalUser(); LocalUser localUser = new LocalUser();
String username = "user" String username = "user" + i;
+ i;
localUser.setUsername(username); localUser.setUsername(username);
localUser.setPasswordHash(passwordEncoder.encode(username)); localUser.setPasswordHash(passwordEncoder.encode(username));
localUserRepository.save(localUser); localUserRepository.save(localUser);
logger.trace("Created user: '" logger.trace("Created user: '" + username + "'");
+ username
+ "'");
} }
logger.info("Created " logger.info("Created " + users + " users");
+ users
+ " users");
for (long id = 0; id <= userCount; id++) { for (long id = 0; id <= userCount; id++) {
entries("user" entries("user" + id, userCount);
+ id, userCount);
} }
logger.warn("finished random generation"); logger.warn("finished random generation");
@ -142,23 +135,16 @@ public class DebugController extends BaseController {
Entry entry = new Entry(); Entry entry = new Entry();
entry.setEntryType(EntryType.INTERN); entry.setEntryType(EntryType.INTERN);
entry.setAuthor(username); entry.setAuthor(username);
entry.setCreated( entry.setCreated(Instant.now().minus(RandomUtils.nextLong(0, entryAge), ChronoUnit.SECONDS));
Instant.now().minus(RandomUtils.nextLong(0, entryAge), ChronoUnit.SECONDS));
entry.setTitle(RandomStringUtils.randomAscii(RandomUtils.nextInt(10, 250))); entry.setTitle(RandomStringUtils.randomAscii(RandomUtils.nextInt(10, 250)));
entry.setText(RandomStringUtils.randomAscii(RandomUtils.nextInt(0, 2500))); entry.setText(RandomStringUtils.randomAscii(RandomUtils.nextInt(0, 2500)));
entry.setEntryStatus(EntryStatus.NORMAL); entry.setEntryStatus(EntryStatus.NORMAL);
entry = entryManager.save(entry); entry = entryManager.save(entry);
logger.trace("Created entry: '" logger.trace("Created entry: '" + entry.getId() + "'");
+ entry.getId()
+ "'");
comments(entry.getId(), entry.getCreated(), userCount); comments(entry.getId(), entry.getCreated(), userCount);
votes(entry.getId(), Types.entry, userCount); votes(entry.getId(), Types.entry, userCount);
} }
logger.info("Created " logger.info("Created " + numEntries + " entries of '" + username + "'");
+ numEntries
+ " entries of '"
+ username
+ "'");
} }
/** /**
@ -170,27 +156,19 @@ public class DebugController extends BaseController {
*/ */
protected void comments(Long target, Instant date, long userCount) { protected void comments(Long target, Instant date, long userCount) {
long numComments = RandomUtils.nextLong(minComments, maxComments); long numComments = RandomUtils.nextLong(minComments, maxComments);
logger.debug("Create " logger.debug("Create " + numComments + " comments for '" + target + "'");
+ numComments
+ " comments for '"
+ target
+ "'");
for (int i = 0; i < numComments; i++) { for (int i = 0; i < numComments; i++) {
Comment comment = new Comment(); Comment comment = new Comment();
comment.setTarget(target); comment.setTarget(target);
comment.setAuthor("user" comment.setAuthor("user" + RandomUtils.nextLong(0, userCount));
+ RandomUtils.nextLong(0, userCount));
comment.setText(RandomStringUtils.randomAscii(RandomUtils.nextInt(0, 2500))); comment.setText(RandomStringUtils.randomAscii(RandomUtils.nextInt(0, 2500)));
comment.setCreated(Instant.now() comment.setCreated(Instant.now().minus(
.minus(RandomUtils.nextLong(0, RandomUtils.nextLong(0, (Instant.now().toEpochMilli() - date.toEpochMilli()) / 1000),
(Instant.now().toEpochMilli() - date.toEpochMilli()) / 1000), ChronoUnit.SECONDS));
ChronoUnit.SECONDS));
comment = commentRepository.save(comment); comment = commentRepository.save(comment);
logger.trace("Created comment: '" logger.trace("Created comment: '" + comment.getId() + "'");
+ comment.getId() subComments(target, comment.getId(), comment.getCreated(), subCommentsFactor, subCommentsThresh, 0,
+ "'"); userCount);
subComments(target, comment.getId(), comment.getCreated(), subCommentsFactor,
subCommentsThresh, 0, userCount);
} }
} }
@ -205,32 +183,24 @@ public class DebugController extends BaseController {
* @param depth the depth * @param depth the depth
* @param userCount the user count * @param userCount the user count
*/ */
protected void subComments(Long target, Long parent, Instant date, float factor, float thresh, protected void subComments(Long target, Long parent, Instant date, float factor, float thresh, int depth,
int depth, long userCount) { long userCount) {
if (depth < subCommentsDepth && RandomUtils.nextFloat(0, 1) < thresh) { if (depth < subCommentsDepth && RandomUtils.nextFloat(0, 1) < thresh) {
long numSubComments = RandomUtils.nextLong(0, Math.round(maxComments * factor)); long numSubComments = RandomUtils.nextLong(0, Math.round(maxComments * factor));
logger.debug("Create " logger.debug("Create " + numSubComments + " subComments for '" + parent + "'");
+ numSubComments
+ " subComments for '"
+ parent
+ "'");
for (int i = 0; i < numSubComments; i++) { for (int i = 0; i < numSubComments; i++) {
Comment comment = new Comment(); Comment comment = new Comment();
comment.setTarget(target); comment.setTarget(target);
comment.setParent(parent); comment.setParent(parent);
comment.setAuthor("user" comment.setAuthor("user" + RandomUtils.nextLong(0, userCount));
+ RandomUtils.nextLong(0, userCount));
comment.setText(RandomStringUtils.randomAscii(RandomUtils.nextInt(0, 2500))); comment.setText(RandomStringUtils.randomAscii(RandomUtils.nextInt(0, 2500)));
comment.setCreated(Instant.now() comment.setCreated(Instant.now().minus(
.minus(RandomUtils.nextLong(0, RandomUtils.nextLong(0, (Instant.now().toEpochMilli() - date.toEpochMilli()) / 1000),
(Instant.now().toEpochMilli() - date.toEpochMilli()) / 1000), ChronoUnit.SECONDS));
ChronoUnit.SECONDS));
comment = commentRepository.save(comment); comment = commentRepository.save(comment);
logger.trace("Created subComment: '" logger.trace("Created subComment: '" + comment.getId() + "'");
+ comment.getId() subComments(target, comment.getId(), comment.getCreated(), factor * 0.5f, thresh * 0.5f, depth++,
+ "'"); userCount);
subComments(target, comment.getId(), comment.getCreated(), factor * 0.5f,
thresh * 0.5f, depth++, userCount);
} }
} }
} }
@ -244,41 +214,27 @@ public class DebugController extends BaseController {
*/ */
protected void votes(Long target, Types targetType, long userCount) { protected void votes(Long target, Types targetType, long userCount) {
long numUpvotes = RandomUtils.nextLong(minUpvotes, maxUpvotes); long numUpvotes = RandomUtils.nextLong(minUpvotes, maxUpvotes);
logger.debug("Create " logger.debug("Create " + numUpvotes + " upvotes for '" + target + "'");
+ numUpvotes
+ " upvotes for '"
+ target
+ "'");
for (int i = 0; i < numUpvotes; i++) { for (int i = 0; i < numUpvotes; i++) {
Vote upvote = new Vote(); Vote upvote = new Vote();
upvote.setTarget(target); upvote.setTarget(target);
upvote.setType(VoteType.up); upvote.setType(VoteType.up);
upvote.setTargetType(targetType); upvote.setTargetType(targetType);
upvote.setAuthor("user" upvote.setAuthor("user" + RandomUtils.nextLong(0, userCount));
+ RandomUtils.nextLong(0, userCount));
upvote = voteRepository.save(upvote); upvote = voteRepository.save(upvote);
logger.trace("Created upvote: '" logger.trace("Created upvote: '" + upvote.getId() + "'");
+ upvote.getId()
+ "'");
} }
long numDownvotes = RandomUtils.nextLong(minDownvotes, maxDownvotes); long numDownvotes = RandomUtils.nextLong(minDownvotes, maxDownvotes);
logger.debug("Create " logger.debug("Create " + numDownvotes + " downvotes for '" + target + "'");
+ numDownvotes
+ " downvotes for '"
+ target
+ "'");
for (int i = 0; i < numDownvotes; i++) { for (int i = 0; i < numDownvotes; i++) {
Vote downvote = new Vote(); Vote downvote = new Vote();
downvote.setTarget(target); downvote.setTarget(target);
downvote.setType(VoteType.down); downvote.setType(VoteType.down);
downvote.setTargetType(targetType); downvote.setTargetType(targetType);
downvote.setAuthor("user" downvote.setAuthor("user" + RandomUtils.nextLong(0, userCount));
+ RandomUtils.nextLong(0, userCount));
downvote = voteRepository.save(downvote); downvote = voteRepository.save(downvote);
logger.trace("Created downvote: '" logger.trace("Created downvote: '" + downvote.getId() + "'");
+ downvote.getId()
+ "'");
} }
} }

View File

@ -68,14 +68,19 @@ public class EntryController extends BaseController {
private ViewManager viewManager; private ViewManager viewManager;
/** /**
* Fetch by user page. * Fetch by view.
* *
* @param name the name * @param name the name
* @param usernameParameter the username parameter * @param usernameParameter the username parameter
* @param pageParameter the page parameter * @param pageParameter the page parameter
* @param sizeParameter the size parameter * @param sizeParameter the size parameter
* @param ascParameter the asc parameter * @param dateParameter the date parameter
* @param ignoreParameter the ignore parameter * @param tagsParameter the tags parameter
* @param excludedTagsParameter the excluded tags parameter
* @param typeParameter the type parameter
* @param gravityParameter the gravity parameter
* @param ascParameter the asc parameter
* @param ignoreParameter the ignore parameter
* @return the page * @return the page
*/ */
@PreAuthorize("isAuthenticated()") @PreAuthorize("isAuthenticated()")
@ -92,8 +97,7 @@ public class EntryController extends BaseController {
@RequestParam("asc") Optional<Boolean> ascParameter, @RequestParam("asc") Optional<Boolean> ascParameter,
@RequestParam("ignore") Optional<List<String>> ignoreParameter) { @RequestParam("ignore") Optional<List<String>> ignoreParameter) {
View view = viewManager.get(usernameParameter.orElse(getCurrentUsername()), View view = viewManager.get(usernameParameter.orElse(getCurrentUsername()), name);
name);
if (view == null || usernameParameter.isPresent() && !view.isPublicView()) { if (view == null || usernameParameter.isPresent() && !view.isPublicView()) {
throw new EntityResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY); throw new EntityResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY);
@ -103,9 +107,8 @@ public class EntryController extends BaseController {
sizeParameter = Optional.of(100); sizeParameter = Optional.of(100);
} }
EntryFilter filter = buildFilter(dateParameter.orElse(null), FlaggedStatus.NORMAL, EntryFilter filter = buildFilter(dateParameter.orElse(null), FlaggedStatus.NORMAL, tagsParameter.orElse(null),
tagsParameter.orElse(null), excludedTagsParameter.orElse(null), excludedTagsParameter.orElse(null), typeParameter.orElse(null));
typeParameter.orElse(null));
filter.setFixedTags(view.getTags()); filter.setFixedTags(view.getTags());
filter.setFixedExcludedTags(view.getExcludedTags()); filter.setFixedExcludedTags(view.getExcludedTags());
@ -114,24 +117,20 @@ public class EntryController extends BaseController {
switch (view.getSorting()) { switch (view.getSorting()) {
case TOP: case TOP:
entries = entryManager.fetchByRanking(getCurrentUsername(), filter, getGravity(), entries = entryManager.fetchByRanking(getCurrentUsername(), filter, getGravity(), pageParameter.orElse(0),
pageParameter.orElse(0), sizeParameter.orElse(settingsManager.getPageSize()), sizeParameter.orElse(settingsManager.getPageSize()), ascParameter.orElse(false));
ascParameter.orElse(false));
break; break;
case NEW: case NEW:
entries = entryManager.fetchByDate(getCurrentUsername(), filter, entries = entryManager.fetchByDate(getCurrentUsername(), filter, pageParameter.orElse(0),
pageParameter.orElse(0), sizeParameter.orElse(settingsManager.getPageSize()), sizeParameter.orElse(settingsManager.getPageSize()), ascParameter.orElse(false));
ascParameter.orElse(false));
break; break;
case HOT: case HOT:
entries = entryManager.fetchByComments(getCurrentUsername(), filter, getGravity(), entries = entryManager.fetchByComments(getCurrentUsername(), filter, getGravity(), pageParameter.orElse(0),
pageParameter.orElse(0), sizeParameter.orElse(settingsManager.getPageSize()), sizeParameter.orElse(settingsManager.getPageSize()), ascParameter.orElse(false));
ascParameter.orElse(false));
break; break;
case LAST: case LAST:
entries = entryManager.fetchByLastComment(getCurrentUsername(), filter, entries = entryManager.fetchByLastComment(getCurrentUsername(), filter, pageParameter.orElse(0),
pageParameter.orElse(0), sizeParameter.orElse(settingsManager.getPageSize()), sizeParameter.orElse(settingsManager.getPageSize()), ascParameter.orElse(false));
ascParameter.orElse(false));
break; break;
} }
@ -179,13 +178,11 @@ public class EntryController extends BaseController {
dateParameter = Optional.of(Instant.now()); dateParameter = Optional.of(Instant.now());
} }
EntryFilter filter = buildFilter(dateParameter.orElse(null), FlaggedStatus.NORMAL, EntryFilter filter = buildFilter(dateParameter.orElse(null), FlaggedStatus.NORMAL, tagsParameter.orElse(null),
tagsParameter.orElse(null), excludedTagsParameter.orElse(null), excludedTagsParameter.orElse(null), typeParameter.orElse(null));
typeParameter.orElse(null));
Page<Entry> entries = entryManager.fetchByUser(getCurrentUsername(), username, filter, Page<Entry> entries = entryManager.fetchByUser(getCurrentUsername(), username, filter, pageParameter.orElse(0),
pageParameter.orElse(0), sizeParameter.orElse(settingsManager.getPageSize()), sizeParameter.orElse(settingsManager.getPageSize()), ascParameter.orElse(false));
ascParameter.orElse(false));
List<String> ignore = ignoreParameter.orElse(Lists.newArrayList()); List<String> ignore = ignoreParameter.orElse(Lists.newArrayList());
entryManager.applyMetadata(getCurrentUsername(), userManager.getKarma(getCurrentUsername()), entryManager.applyMetadata(getCurrentUsername(), userManager.getKarma(getCurrentUsername()),
entries.getContent(), ignore); entries.getContent(), ignore);
@ -222,8 +219,7 @@ public class EntryController extends BaseController {
*/ */
@PreAuthorize("isAuthenticated()") @PreAuthorize("isAuthenticated()")
@GetMapping("/entry/{id}") @GetMapping("/entry/{id}")
public Entry getEntry(@PathVariable("id") Long id, public Entry getEntry(@PathVariable("id") Long id, @RequestParam("ignore") Optional<List<String>> ignoreParameter) {
@RequestParam("ignore") Optional<List<String>> ignoreParameter) {
Entry entry = entryManager.get(id); Entry entry = entryManager.get(id);
if (entry == null) { if (entry == null) {
@ -231,8 +227,7 @@ public class EntryController extends BaseController {
} }
List<String> ignore = ignoreParameter.orElse(Lists.newArrayList()); List<String> ignore = ignoreParameter.orElse(Lists.newArrayList());
entryManager.applyMetadata(getCurrentUsername(), userManager.getKarma(getCurrentUsername()), entryManager.applyMetadata(getCurrentUsername(), userManager.getKarma(getCurrentUsername()), entry, ignore);
entry, ignore);
return entry; return entry;
} }
@ -246,14 +241,12 @@ public class EntryController extends BaseController {
*/ */
@PreAuthorize("isAuthenticated()") @PreAuthorize("isAuthenticated()")
@PostMapping() @PostMapping()
public Entry createEntry(@RequestBody Entry entry, public Entry createEntry(@RequestBody Entry entry, @RequestParam("ignore") Optional<List<String>> ignoreParameter) {
@RequestParam("ignore") Optional<List<String>> ignoreParameter) {
RequestBodyErrors bindingResult = new RequestBodyErrors(entry); RequestBodyErrors bindingResult = new RequestBodyErrors(entry);
entryValidator.validate(entry, bindingResult); entryValidator.validate(entry, bindingResult);
if (bindingResult.hasErrors()) { if (bindingResult.hasErrors()) {
throw new EntityResponseStatusException(bindingResult.getAllErrors(), throw new EntityResponseStatusException(bindingResult.getAllErrors(), HttpStatus.UNPROCESSABLE_ENTITY);
HttpStatus.UNPROCESSABLE_ENTITY);
} }
entry.setCreated(Instant.now().plus(getEntryDelay(), ChronoUnit.MINUTES)); entry.setCreated(Instant.now().plus(getEntryDelay(), ChronoUnit.MINUTES));
@ -272,8 +265,7 @@ public class EntryController extends BaseController {
voteManager.save(vote); voteManager.save(vote);
List<String> ignore = ignoreParameter.orElse(Lists.newArrayList()); List<String> ignore = ignoreParameter.orElse(Lists.newArrayList());
entryManager.applyMetadata(getCurrentUsername(), userManager.getKarma(getCurrentUsername()), entryManager.applyMetadata(getCurrentUsername(), userManager.getKarma(getCurrentUsername()), entry, ignore);
entry, ignore);
return entry; return entry;
} }
@ -287,11 +279,10 @@ public class EntryController extends BaseController {
*/ */
@PreAuthorize("isAuthenticated()") @PreAuthorize("isAuthenticated()")
@PatchMapping @PatchMapping
public Entry updateEntry(@RequestBody Entry entry, public Entry updateEntry(@RequestBody Entry entry, @RequestParam("ignore") Optional<List<String>> ignoreParameter) {
@RequestParam("ignore") Optional<List<String>> ignoreParameter) {
Entry orgEntry = entryManager.get(entry.getId()); Entry orgEntry = entryManager.get(entry.getId());
if (orgEntry == null || !orgEntry.getAuthor().equals(getCurrentUsername()) || orgEntry if (orgEntry == null || !orgEntry.getAuthor().equals(getCurrentUsername())
.getCreated().plus(getEntryDelay(), ChronoUnit.MINUTES).isBefore(Instant.now())) { || orgEntry.getCreated().plus(getEntryDelay(), ChronoUnit.MINUTES).isBefore(Instant.now())) {
throw new EntityResponseStatusException(HttpStatus.FORBIDDEN); throw new EntityResponseStatusException(HttpStatus.FORBIDDEN);
} }
@ -299,8 +290,7 @@ public class EntryController extends BaseController {
entryValidator.validate(entry, bindingResult); entryValidator.validate(entry, bindingResult);
if (bindingResult.hasErrors()) { if (bindingResult.hasErrors()) {
throw new EntityResponseStatusException(bindingResult.getAllErrors(), throw new EntityResponseStatusException(bindingResult.getAllErrors(), HttpStatus.UNPROCESSABLE_ENTITY);
HttpStatus.UNPROCESSABLE_ENTITY);
} }
orgEntry.setUrl(entry.getUrl()); orgEntry.setUrl(entry.getUrl());
@ -310,8 +300,7 @@ public class EntryController extends BaseController {
orgEntry = entryManager.save(orgEntry); orgEntry = entryManager.save(orgEntry);
List<String> ignore = ignoreParameter.orElse(Lists.newArrayList()); List<String> ignore = ignoreParameter.orElse(Lists.newArrayList());
entryManager.applyMetadata(getCurrentUsername(), userManager.getKarma(getCurrentUsername()), entryManager.applyMetadata(getCurrentUsername(), userManager.getKarma(getCurrentUsername()), orgEntry, ignore);
orgEntry, ignore);
return orgEntry; return orgEntry;
} }
@ -324,8 +313,8 @@ public class EntryController extends BaseController {
@DeleteMapping("{id}") @DeleteMapping("{id}")
public void deteleEntry(@PathVariable("id") Long id) { public void deteleEntry(@PathVariable("id") Long id) {
Entry orgEntry = entryManager.get(id); Entry orgEntry = entryManager.get(id);
if (orgEntry == null || !orgEntry.getAuthor().equals(getCurrentUsername()) || orgEntry if (orgEntry == null || !orgEntry.getAuthor().equals(getCurrentUsername())
.getCreated().plus(getEntryDelay(), ChronoUnit.MINUTES).isBefore(Instant.now())) { || orgEntry.getCreated().plus(getEntryDelay(), ChronoUnit.MINUTES).isBefore(Instant.now())) {
throw new EntityResponseStatusException(HttpStatus.FORBIDDEN); throw new EntityResponseStatusException(HttpStatus.FORBIDDEN);
} }
@ -347,8 +336,7 @@ public class EntryController extends BaseController {
response = new URL(URLDecoder.decode(url, "utf-8")).openStream(); response = new URL(URLDecoder.decode(url, "utf-8")).openStream();
scanner = new Scanner(response); scanner = new Scanner(response);
String responseBody = scanner.useDelimiter("\\A").next(); String responseBody = scanner.useDelimiter("\\A").next();
return responseBody.substring(responseBody.indexOf("<title>") + 7, return responseBody.substring(responseBody.indexOf("<title>") + 7, responseBody.indexOf("</title>"));
responseBody.indexOf("</title>"));
} catch (IOException ex) { } catch (IOException ex) {
} finally { } finally {
try { try {

View File

@ -52,17 +52,16 @@ public class ModerationController extends BaseController {
/** /**
* Gets the flagged comments. * Gets the flagged comments.
* *
* @param pageParameter the page parameter * @param pageParameter the page parameter
* @param sizeParameter the size parameter * @param sizeParameter the size parameter
* @param ascParameter the asc parameter * @param ascParameter the asc parameter
* @param ignoreParameter the ignore parameter * @param ignoreParameter the ignore parameter
* @return the flagged comments * @return the flagged comments
*/ */
@PreAuthorize("hasRole('ROLE_ADMIN') || hasRole('ROLE_MOD')") @PreAuthorize("hasRole('ROLE_ADMIN') || hasRole('ROLE_MOD')")
@GetMapping("/flags/comments") @GetMapping("/flags/comments")
public Page<Comment> getFlaggedComments(@RequestParam("page") Optional<Integer> pageParameter, public Page<Comment> getFlaggedComments(@RequestParam("page") Optional<Integer> pageParameter,
@RequestParam("size") Optional<Integer> sizeParameter, @RequestParam("size") Optional<Integer> sizeParameter, @RequestParam("asc") Optional<Boolean> ascParameter,
@RequestParam("asc") Optional<Boolean> ascParameter,
@RequestParam("ignore") Optional<List<String>> ignoreParameter) { @RequestParam("ignore") Optional<List<String>> ignoreParameter) {
if (sizeParameter.isPresent() && sizeParameter.get() > 100) { if (sizeParameter.isPresent() && sizeParameter.get() > 100) {
sizeParameter = Optional.of(100); sizeParameter = Optional.of(100);
@ -78,17 +77,16 @@ public class ModerationController extends BaseController {
/** /**
* Gets the flagged entries. * Gets the flagged entries.
* *
* @param pageParameter the page parameter * @param pageParameter the page parameter
* @param sizeParameter the size parameter * @param sizeParameter the size parameter
* @param ascParameter the asc parameter * @param ascParameter the asc parameter
* @param ignoreParameter the ignore parameter * @param ignoreParameter the ignore parameter
* @return the flagged entries * @return the flagged entries
*/ */
@PreAuthorize("hasRole('ROLE_ADMIN') || hasRole('ROLE_MOD')") @PreAuthorize("hasRole('ROLE_ADMIN') || hasRole('ROLE_MOD')")
@GetMapping("/flags/entries") @GetMapping("/flags/entries")
public Page<Entry> getFlaggedEntries(@RequestParam("page") Optional<Integer> pageParameter, public Page<Entry> getFlaggedEntries(@RequestParam("page") Optional<Integer> pageParameter,
@RequestParam("size") Optional<Integer> sizeParameter, @RequestParam("size") Optional<Integer> sizeParameter, @RequestParam("asc") Optional<Boolean> ascParameter,
@RequestParam("asc") Optional<Boolean> ascParameter,
@RequestParam("ignore") Optional<List<String>> ignoreParameter) { @RequestParam("ignore") Optional<List<String>> ignoreParameter) {
if (sizeParameter.isPresent() && sizeParameter.get() > 100) { if (sizeParameter.isPresent() && sizeParameter.get() > 100) {
sizeParameter = Optional.of(100); sizeParameter = Optional.of(100);
@ -96,7 +94,8 @@ public class ModerationController extends BaseController {
Page<Entry> entries = entryManager.fetchFlagged(pageParameter.orElse(0), Page<Entry> entries = entryManager.fetchFlagged(pageParameter.orElse(0),
sizeParameter.orElse(settingsManager.getPageSize()), ascParameter.orElse(false)); sizeParameter.orElse(settingsManager.getPageSize()), ascParameter.orElse(false));
List<String> ignore = ignoreParameter.orElse(Lists.newArrayList("flag", "unflag", "bookmark", "removeBookmark")); List<String> ignore = ignoreParameter
.orElse(Lists.newArrayList("flag", "unflag", "bookmark", "removeBookmark"));
entryManager.applyMetadata(getCurrentUsername(), userManager.getKarma(getCurrentUsername()), entryManager.applyMetadata(getCurrentUsername(), userManager.getKarma(getCurrentUsername()),
entries.getContent(), ignore); entries.getContent(), ignore);
return entries; return entries;

View File

@ -29,8 +29,7 @@ import de.bstly.board.model.Entry;
import de.bstly.board.model.support.Types; import de.bstly.board.model.support.Types;
/** /**
* @author _bastler@bstly.de * The Class SearchController.
*
*/ */
@RestController @RestController
@RequestMapping("/search") @RequestMapping("/search")
@ -51,6 +50,7 @@ public class SearchController extends BaseController {
* Search. * Search.
* *
* @param searchParameter the search parameter * @param searchParameter the search parameter
* @param typeParameter the type parameter
* @param pageParameter the page parameter * @param pageParameter the page parameter
* @param sizeParameter the size parameter * @param sizeParameter the size parameter
* @param byDateParameter the by date parameter * @param byDateParameter the by date parameter
@ -61,8 +61,7 @@ public class SearchController extends BaseController {
@PreAuthorize("isAuthenticated()") @PreAuthorize("isAuthenticated()")
@GetMapping @GetMapping
public Page<Object> search(@RequestParam("q") String searchParameter, public Page<Object> search(@RequestParam("q") String searchParameter,
@RequestParam("type") Optional<String> typeParameter, @RequestParam("type") Optional<String> typeParameter, @RequestParam("page") Optional<Integer> pageParameter,
@RequestParam("page") Optional<Integer> pageParameter,
@RequestParam("size") Optional<Integer> sizeParameter, @RequestParam("size") Optional<Integer> sizeParameter,
@RequestParam("byDate") Optional<Boolean> byDateParameter, @RequestParam("byDate") Optional<Boolean> byDateParameter,
@RequestParam("asc") Optional<Boolean> ascParameter, @RequestParam("asc") Optional<Boolean> ascParameter,
@ -89,21 +88,20 @@ public class SearchController extends BaseController {
break; break;
} }
SearchResult<Object> result = searchManager.search(types, searchParameter, SearchResult<Object> result = searchManager.search(types, searchParameter, pageParameter.orElse(0),
pageParameter.orElse(0), sizeParameter.orElse(settingsManager.getPageSize()), sizeParameter.orElse(settingsManager.getPageSize()), ascParameter.orElse(false),
ascParameter.orElse(false), byDateParameter.orElse(false)); byDateParameter.orElse(false));
Page<Object> objects = new PageImpl<Object>(result.hits(), Page<Object> objects = new PageImpl<Object>(result.hits(),
PageRequest.of(pageParameter.orElse(0), PageRequest.of(pageParameter.orElse(0), sizeParameter.orElse(settingsManager.getPageSize())),
sizeParameter.orElse(settingsManager.getPageSize())),
result.total().hitCount()); result.total().hitCount());
List<String> ignore = ignoreParameter.orElse(Lists.newArrayList()); List<String> ignore = ignoreParameter.orElse(Lists.newArrayList());
for (Object object : objects) { for (Object object : objects) {
if (object instanceof Entry) { if (object instanceof Entry) {
entryManager.applyMetadata(getCurrentUsername(), entryManager.applyMetadata(getCurrentUsername(), userManager.getKarma(getCurrentUsername()),
userManager.getKarma(getCurrentUsername()), (Entry) object, ignore); (Entry) object, ignore);
} else if (object instanceof Comment) { } else if (object instanceof Comment) {
commentManager.applyMetadata(getCurrentUsername(), (Comment) object, ignore); commentManager.applyMetadata(getCurrentUsername(), (Comment) object, ignore);
} }

View File

@ -58,8 +58,8 @@ public class TagController extends BaseController {
/** /**
* Sets the tags. * Sets the tags.
* *
* @param id the id * @param id the id
* @param tags the tags * @param tags the tags
* @param ignoreParameter the ignore parameter * @param ignoreParameter the ignore parameter
* @return the entry * @return the entry
*/ */
@ -78,15 +78,13 @@ public class TagController extends BaseController {
entryValidator.validate(entry, bindingResult); entryValidator.validate(entry, bindingResult);
if (bindingResult.hasErrors()) { if (bindingResult.hasErrors()) {
throw new EntityResponseStatusException(bindingResult.getAllErrors(), throw new EntityResponseStatusException(bindingResult.getAllErrors(), HttpStatus.UNPROCESSABLE_ENTITY);
HttpStatus.UNPROCESSABLE_ENTITY);
} }
entry = entryManager.save(entry); entry = entryManager.save(entry);
List<String> ignore = ignoreParameter.orElse(Lists.newArrayList()); List<String> ignore = ignoreParameter.orElse(Lists.newArrayList());
entryManager.applyMetadata(getCurrentUsername(), userManager.getKarma(getCurrentUsername()), entryManager.applyMetadata(getCurrentUsername(), userManager.getKarma(getCurrentUsername()), entry, ignore);
entry, ignore);
return entry; return entry;
} }

View File

@ -19,7 +19,6 @@ import de.bstly.board.businesslogic.UserManager;
import de.bstly.board.controller.support.EntityResponseStatusException; import de.bstly.board.controller.support.EntityResponseStatusException;
import de.bstly.board.model.LocalUser; import de.bstly.board.model.LocalUser;
/** /**
* The Class UserController. * The Class UserController.
*/ */
@ -27,7 +26,6 @@ import de.bstly.board.model.LocalUser;
@RequestMapping("/users") @RequestMapping("/users")
public class UserController extends BaseController { public class UserController extends BaseController {
@Autowired @Autowired
private UserManager userManager; private UserManager userManager;

View File

@ -40,12 +40,12 @@ public class ViewController extends BaseController {
private ViewValidator viewValidator; private ViewValidator viewValidator;
/** /**
* Gets the user pages. * Gets the views.
* *
* @param pageParameter the page parameter * @param pageParameter the page parameter
* @param sizeParameter the size parameter * @param sizeParameter the size parameter
* @param descParameter the desc parameter * @param descParameter the desc parameter
* @return the user pages * @return the views
*/ */
@PreAuthorize("isAuthenticated()") @PreAuthorize("isAuthenticated()")
@GetMapping() @GetMapping()
@ -62,12 +62,12 @@ public class ViewController extends BaseController {
} }
/** /**
* Gets the public user pages. * Gets the public views.
* *
* @param pageParameter the page parameter * @param pageParameter the page parameter
* @param sizeParameter the size parameter * @param sizeParameter the size parameter
* @param descParameter the desc parameter * @param descParameter the desc parameter
* @return the public user pages * @return the public views
*/ */
@PreAuthorize("isAuthenticated()") @PreAuthorize("isAuthenticated()")
@GetMapping("/public") @GetMapping("/public")
@ -75,20 +75,19 @@ public class ViewController extends BaseController {
@RequestParam("size") Optional<Integer> sizeParameter, @RequestParam("size") Optional<Integer> sizeParameter,
@RequestParam("desc") Optional<Boolean> descParameter) { @RequestParam("desc") Optional<Boolean> descParameter) {
return viewManager.getPublic(getCurrentUsername(), pageParameter.orElse(0), return viewManager.getPublic(getCurrentUsername(), pageParameter.orElse(0),
sizeParameter.orElse(settingsManager.getPageSize()), "name", sizeParameter.orElse(settingsManager.getPageSize()), "name", descParameter.orElse(false));
descParameter.orElse(false));
} }
/** /**
* Gets the user page. * Gets the view.
* *
* @param name the name * @param name the name
* @return the user page * @param usernameParameter the username parameter
* @return the view
*/ */
@PreAuthorize("isAuthenticated()") @PreAuthorize("isAuthenticated()")
@GetMapping("/view/{name}") @GetMapping("/view/{name}")
public View getView(@PathVariable("name") String name, public View getView(@PathVariable("name") String name, @RequestParam("user") Optional<String> usernameParameter) {
@RequestParam("user") Optional<String> usernameParameter) {
View view = viewManager.get(usernameParameter.orElse(getCurrentUsername()), name); View view = viewManager.get(usernameParameter.orElse(getCurrentUsername()), name);
if (view == null || usernameParameter.isPresent() && !view.isPublicView()) { if (view == null || usernameParameter.isPresent() && !view.isPublicView()) {
@ -101,8 +100,8 @@ public class ViewController extends BaseController {
/** /**
* Creates the or update. * Creates the or update.
* *
* @param view the user page * @param view the view
* @return the user page * @return the view
*/ */
@PreAuthorize("isAuthenticated()") @PreAuthorize("isAuthenticated()")
@PostMapping("/view") @PostMapping("/view")
@ -113,8 +112,7 @@ public class ViewController extends BaseController {
viewValidator.validate(view, bindingResult); viewValidator.validate(view, bindingResult);
if (bindingResult.hasErrors()) { if (bindingResult.hasErrors()) {
throw new EntityResponseStatusException(bindingResult.getAllErrors(), throw new EntityResponseStatusException(bindingResult.getAllErrors(), HttpStatus.UNPROCESSABLE_ENTITY);
HttpStatus.UNPROCESSABLE_ENTITY);
} }
if (!viewManager.exists(getCurrentUsername(), view.getName()) if (!viewManager.exists(getCurrentUsername(), view.getName())
@ -126,7 +124,7 @@ public class ViewController extends BaseController {
} }
/** /**
* Delete user page. * Delete view.
* *
* @param name the name * @param name the name
*/ */

View File

@ -96,28 +96,36 @@ public class EntryFilter {
} }
/** /**
* @return the fixedTags * Gets the fixed tags.
*
* @return the fixed tags
*/ */
public List<String> getFixedTags() { public List<String> getFixedTags() {
return fixedTags; return fixedTags;
} }
/** /**
* @param fixedTags the fixedTags to set * Sets the fixed tags.
*
* @param fixedTags the new fixed tags
*/ */
public void setFixedTags(List<String> fixedTags) { public void setFixedTags(List<String> fixedTags) {
this.fixedTags = fixedTags; this.fixedTags = fixedTags;
} }
/** /**
* @return the fixedExcludedTags * Gets the fixed excluded tags.
*
* @return the fixed excluded tags
*/ */
public List<String> getFixedExcludedTags() { public List<String> getFixedExcludedTags() {
return fixedExcludedTags; return fixedExcludedTags;
} }
/** /**
* @param fixedExcludedTags the fixedExcludedTags to set * Sets the fixed excluded tags.
*
* @param fixedExcludedTags the new fixed excluded tags
*/ */
public void setFixedExcludedTags(List<String> fixedExcludedTags) { public void setFixedExcludedTags(List<String> fixedExcludedTags) {
this.fixedExcludedTags = fixedExcludedTags; this.fixedExcludedTags = fixedExcludedTags;

View File

@ -10,7 +10,6 @@ import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest; import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
/** /**
* The Class ControllerExceptionHandler. * The Class ControllerExceptionHandler.
*/ */
@ -21,15 +20,15 @@ public class ControllerExceptionHandler extends ResponseEntityExceptionHandler {
* Handle response entity status exception. * Handle response entity status exception.
* *
* @param exception the exception * @param exception the exception
* @param request the request * @param request the request
* @return the response entity * @return the response entity
*/ */
@ExceptionHandler(value = { EntityResponseStatusException.class }) @ExceptionHandler(value = { EntityResponseStatusException.class })
protected ResponseEntity<Object> handleResponseEntityStatusException(RuntimeException exception, protected ResponseEntity<Object> handleResponseEntityStatusException(RuntimeException exception,
WebRequest request) { WebRequest request) {
EntityResponseStatusException entityResponseStatusException = (EntityResponseStatusException) exception; EntityResponseStatusException entityResponseStatusException = (EntityResponseStatusException) exception;
return handleExceptionInternal(exception, entityResponseStatusException.getBody(), return handleExceptionInternal(exception, entityResponseStatusException.getBody(), new HttpHeaders(),
new HttpHeaders(), entityResponseStatusException.getStatus(), request); entityResponseStatusException.getStatus(), request);
} }
} }

View File

@ -10,19 +10,15 @@ import org.springframework.core.NestedRuntimeException;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.util.Assert; import org.springframework.util.Assert;
/** /**
* The Class EntityResponseStatusException. * The Class EntityResponseStatusException.
*/ */
public class EntityResponseStatusException extends NestedRuntimeException { public class EntityResponseStatusException extends NestedRuntimeException {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private final HttpStatus status; private final HttpStatus status;
@Nullable @Nullable
private final Object body; private final Object body;
@ -38,7 +34,7 @@ public class EntityResponseStatusException extends NestedRuntimeException {
/** /**
* Instantiates a new entity response status exception. * Instantiates a new entity response status exception.
* *
* @param body the body * @param body the body
* @param status the status * @param status the status
*/ */
public EntityResponseStatusException(@Nullable Object body, HttpStatus status) { public EntityResponseStatusException(@Nullable Object body, HttpStatus status) {
@ -48,9 +44,9 @@ public class EntityResponseStatusException extends NestedRuntimeException {
/** /**
* Instantiates a new entity response status exception. * Instantiates a new entity response status exception.
* *
* @param body the body * @param body the body
* @param status the status * @param status the status
* @param cause the cause * @param cause the cause
*/ */
public EntityResponseStatusException(@Nullable Object body, HttpStatus status, @Nullable Throwable cause) { public EntityResponseStatusException(@Nullable Object body, HttpStatus status, @Nullable Throwable cause) {
super(null, cause); super(null, cause);
@ -78,7 +74,6 @@ public class EntityResponseStatusException extends NestedRuntimeException {
return this.body; return this.body;
} }
/* /*
* @see org.springframework.core.NestedRuntimeException#getMessage() * @see org.springframework.core.NestedRuntimeException#getMessage()
*/ */

View File

@ -29,9 +29,10 @@ public class JsonStringBodyControllerAdvice implements RequestBodyAdvice, Respon
private Gson gson = new Gson(); private Gson gson = new Gson();
/* /*
* @see org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice#supports(org.springframework.core.MethodParameter, java.lang.reflect.Type, java.lang.Class) * @see org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice#
* supports(org.springframework.core.MethodParameter, java.lang.reflect.Type,
* java.lang.Class)
*/ */
@Override @Override
public boolean supports(MethodParameter methodParameter, Type targetType, public boolean supports(MethodParameter methodParameter, Type targetType,
@ -39,9 +40,11 @@ public class JsonStringBodyControllerAdvice implements RequestBodyAdvice, Respon
return targetType instanceof Class && String.class.equals((Class<?>) targetType); return targetType instanceof Class && String.class.equals((Class<?>) targetType);
} }
/* /*
* @see org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice#beforeBodyRead(org.springframework.http.HttpInputMessage, org.springframework.core.MethodParameter, java.lang.reflect.Type, java.lang.Class) * @see org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice#
* beforeBodyRead(org.springframework.http.HttpInputMessage,
* org.springframework.core.MethodParameter, java.lang.reflect.Type,
* java.lang.Class)
*/ */
@Override @Override
public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
@ -49,9 +52,11 @@ public class JsonStringBodyControllerAdvice implements RequestBodyAdvice, Respon
return inputMessage; return inputMessage;
} }
/* /*
* @see org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice#afterBodyRead(java.lang.Object, org.springframework.http.HttpInputMessage, org.springframework.core.MethodParameter, java.lang.reflect.Type, java.lang.Class) * @see org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice#
* afterBodyRead(java.lang.Object, org.springframework.http.HttpInputMessage,
* org.springframework.core.MethodParameter, java.lang.reflect.Type,
* java.lang.Class)
*/ */
@Override @Override
public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
@ -60,9 +65,11 @@ public class JsonStringBodyControllerAdvice implements RequestBodyAdvice, Respon
return body; return body;
} }
/* /*
* @see org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice#handleEmptyBody(java.lang.Object, org.springframework.http.HttpInputMessage, org.springframework.core.MethodParameter, java.lang.reflect.Type, java.lang.Class) * @see org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice#
* handleEmptyBody(java.lang.Object, org.springframework.http.HttpInputMessage,
* org.springframework.core.MethodParameter, java.lang.reflect.Type,
* java.lang.Class)
*/ */
@Override @Override
public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
@ -70,18 +77,23 @@ public class JsonStringBodyControllerAdvice implements RequestBodyAdvice, Respon
return body; return body;
} }
/* /*
* @see org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice#supports(org.springframework.core.MethodParameter, java.lang.Class) * @see
* org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice#
* supports(org.springframework.core.MethodParameter, java.lang.Class)
*/ */
@Override @Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) { public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return converterType == StringHttpMessageConverter.class; return converterType == StringHttpMessageConverter.class;
} }
/* /*
* @see org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice#beforeBodyWrite(java.lang.Object, org.springframework.core.MethodParameter, org.springframework.http.MediaType, java.lang.Class, org.springframework.http.server.ServerHttpRequest, org.springframework.http.server.ServerHttpResponse) * @see
* org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice#
* beforeBodyWrite(java.lang.Object, org.springframework.core.MethodParameter,
* org.springframework.http.MediaType, java.lang.Class,
* org.springframework.http.server.ServerHttpRequest,
* org.springframework.http.server.ServerHttpResponse)
*/ */
@Override @Override
public String beforeBodyWrite(String body, MethodParameter returnType, MediaType selectedContentType, public String beforeBodyWrite(String body, MethodParameter returnType, MediaType selectedContentType,

View File

@ -6,14 +6,12 @@ package de.bstly.board.controller.support;
import org.springframework.lang.Nullable; import org.springframework.lang.Nullable;
import org.springframework.validation.AbstractBindingResult; import org.springframework.validation.AbstractBindingResult;
/** /**
* The Class RequestBodyErrors. * The Class RequestBodyErrors.
*/ */
@SuppressWarnings("serial") @SuppressWarnings("serial")
public class RequestBodyErrors extends AbstractBindingResult { public class RequestBodyErrors extends AbstractBindingResult {
@Nullable @Nullable
private final Object target; private final Object target;
@ -35,9 +33,10 @@ public class RequestBodyErrors extends AbstractBindingResult {
return target; return target;
} }
/* /*
* @see org.springframework.validation.AbstractBindingResult#getActualFieldValue(java.lang.String) * @see
* org.springframework.validation.AbstractBindingResult#getActualFieldValue(java
* .lang.String)
*/ */
@Override @Override
protected Object getActualFieldValue(String field) { protected Object getActualFieldValue(String field) {

View File

@ -13,7 +13,6 @@ import de.bstly.board.businesslogic.CommentManager;
import de.bstly.board.businesslogic.EntryManager; import de.bstly.board.businesslogic.EntryManager;
import de.bstly.board.model.Comment; import de.bstly.board.model.Comment;
/** /**
* The Class CommentValidator. * The Class CommentValidator.
*/ */
@ -25,7 +24,6 @@ public class CommentValidator implements Validator {
@Autowired @Autowired
private EntryManager entryManager; private EntryManager entryManager;
/* /*
* @see org.springframework.validation.Validator#supports(java.lang.Class) * @see org.springframework.validation.Validator#supports(java.lang.Class)
*/ */
@ -34,9 +32,9 @@ public class CommentValidator implements Validator {
return clazz.isAssignableFrom(Comment.class); return clazz.isAssignableFrom(Comment.class);
} }
/* /*
* @see org.springframework.validation.Validator#validate(java.lang.Object, org.springframework.validation.Errors) * @see org.springframework.validation.Validator#validate(java.lang.Object,
* org.springframework.validation.Errors)
*/ */
@Override @Override
public void validate(Object target, Errors errors) { public void validate(Object target, Errors errors) {

View File

@ -41,11 +41,9 @@ public class EntryValidator implements Validator {
if (entry.getEntryType() == null) { if (entry.getEntryType() == null) {
errors.rejectValue("entrytype", "REQUIRED"); errors.rejectValue("entrytype", "REQUIRED");
} else if (EntryType.LINK.equals(entry.getEntryType()) } else if (EntryType.LINK.equals(entry.getEntryType()) && !StringUtils.hasText(entry.getUrl())) {
&& !StringUtils.hasText(entry.getUrl())) {
errors.rejectValue("url", "REQUIRED"); errors.rejectValue("url", "REQUIRED");
} else if (!EntryType.LINK.equals(entry.getEntryType()) } else if (!EntryType.LINK.equals(entry.getEntryType()) && !StringUtils.hasText(entry.getText())) {
&& !StringUtils.hasText(entry.getText())) {
errors.rejectValue("text", "REQUIRED"); errors.rejectValue("text", "REQUIRED");
} }

View File

@ -7,13 +7,11 @@ import org.springframework.context.ApplicationEvent;
import de.bstly.board.model.Vote; import de.bstly.board.model.Vote;
/** /**
* The Class VotedEvent. * The Class VotedEvent.
*/ */
public class VotedEvent extends ApplicationEvent { public class VotedEvent extends ApplicationEvent {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** /**

View File

@ -28,25 +28,20 @@ import com.google.gson.JsonParser;
import de.bstly.board.i18n.model.I18n; import de.bstly.board.i18n.model.I18n;
import de.bstly.board.i18n.repository.I18nRepository; import de.bstly.board.i18n.repository.I18nRepository;
/** /**
* The Class I18nManager. * The Class I18nManager.
*/ */
@Component @Component
public class I18nManager implements SmartInitializingSingleton { public class I18nManager implements SmartInitializingSingleton {
private Logger logger = LoggerFactory.getLogger(I18nManager.class); private Logger logger = LoggerFactory.getLogger(I18nManager.class);
@Autowired @Autowired
private I18nRepository i18nRepository; private I18nRepository i18nRepository;
@Autowired @Autowired
private ResourceLoader resourceLoader; private ResourceLoader resourceLoader;
private Gson gson = new Gson(); private Gson gson = new Gson();
/** /**
@ -90,7 +85,7 @@ public class I18nManager implements SmartInitializingSingleton {
* Extend json object. * Extend json object.
* *
* @param dest the dest * @param dest the dest
* @param src the src * @param src the src
*/ */
protected void extendJsonObject(JsonObject dest, JsonObject src) { protected void extendJsonObject(JsonObject dest, JsonObject src) {
for (Entry<String, JsonElement> srcEntry : src.entrySet()) { for (Entry<String, JsonElement> srcEntry : src.entrySet()) {
@ -112,7 +107,7 @@ public class I18nManager implements SmartInitializingSingleton {
/** /**
* Adds the label. * Adds the label.
* *
* @param locale the locale * @param locale the locale
* @param newLabel the new label * @param newLabel the new label
* @return the i 18 n * @return the i 18 n
*/ */
@ -136,7 +131,7 @@ public class I18nManager implements SmartInitializingSingleton {
* Sets the label. * Sets the label.
* *
* @param locale the locale * @param locale the locale
* @param label the label * @param label the label
* @return the i 18 n * @return the i 18 n
*/ */
public I18n setLabel(String locale, JsonObject label) { public I18n setLabel(String locale, JsonObject label) {
@ -158,9 +153,9 @@ public class I18nManager implements SmartInitializingSingleton {
} }
} }
/* /*
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated() * @see org.springframework.beans.factory.SmartInitializingSingleton#
* afterSingletonsInstantiated()
*/ */
@Override @Override
public void afterSingletonsInstantiated() { public void afterSingletonsInstantiated() {
@ -171,8 +166,7 @@ public class I18nManager implements SmartInitializingSingleton {
File labelFolder = resource.getFile(); File labelFolder = resource.getFile();
if (labelFolder.exists() && labelFolder.isDirectory()) { if (labelFolder.exists() && labelFolder.isDirectory()) {
for (File labelFile : labelFolder.listFiles()) { for (File labelFile : labelFolder.listFiles()) {
JsonObject label = JsonParser JsonObject label = JsonParser.parseReader(new FileReader(labelFile, StandardCharsets.UTF_8))
.parseReader(new FileReader(labelFile, StandardCharsets.UTF_8))
.getAsJsonObject(); .getAsJsonObject();
String locale = labelFile.getName().replace(".json", ""); String locale = labelFile.getName().replace(".json", "");

View File

@ -27,7 +27,6 @@ import com.google.gson.JsonObject;
import de.bstly.board.controller.BaseController; import de.bstly.board.controller.BaseController;
import de.bstly.board.i18n.businesslogic.I18nManager; import de.bstly.board.i18n.businesslogic.I18nManager;
/** /**
* The Class I18nController. * The Class I18nController.
*/ */
@ -35,11 +34,9 @@ import de.bstly.board.i18n.businesslogic.I18nManager;
@RequestMapping("/i18n") @RequestMapping("/i18n")
public class I18nController extends BaseController { public class I18nController extends BaseController {
@Autowired @Autowired
private I18nManager i18nManager; private I18nManager i18nManager;
private Gson gson = new Gson(); private Gson gson = new Gson();
/** /**
@ -55,11 +52,11 @@ public class I18nController extends BaseController {
/** /**
* Gets the label. * Gets the label.
* *
* @param locale the locale * @param locale the locale
* @param response the response * @param response the response
* @return the label * @return the label
* @throws JsonIOException the json IO exception * @throws JsonIOException the json IO exception
* @throws IOException Signals that an I/O exception has occurred. * @throws IOException Signals that an I/O exception has occurred.
*/ */
@GetMapping("/{locale}") @GetMapping("/{locale}")
public void getLabel(@PathVariable("locale") String locale, HttpServletResponse response) public void getLabel(@PathVariable("locale") String locale, HttpServletResponse response)
@ -75,7 +72,7 @@ public class I18nController extends BaseController {
* Sets the label. * Sets the label.
* *
* @param locale the locale * @param locale the locale
* @param label the label * @param label the label
*/ */
@PreAuthorize("hasRole('ROLE_ADMIN')") @PreAuthorize("hasRole('ROLE_ADMIN')")
@PostMapping("/{locale}") @PostMapping("/{locale}")
@ -91,7 +88,7 @@ public class I18nController extends BaseController {
* Adds the label. * Adds the label.
* *
* @param locale the locale * @param locale the locale
* @param label the label * @param label the label
*/ */
@PreAuthorize("hasRole('ROLE_ADMIN')") @PreAuthorize("hasRole('ROLE_ADMIN')")
@PutMapping("/{locale}") @PutMapping("/{locale}")

View File

@ -10,7 +10,6 @@ import javax.persistence.Lob;
import javax.persistence.Table; import javax.persistence.Table;
import javax.persistence.UniqueConstraint; import javax.persistence.UniqueConstraint;
/** /**
* The Class I18n. * The Class I18n.
*/ */
@ -18,12 +17,10 @@ import javax.persistence.UniqueConstraint;
@Table(name = "i18n", uniqueConstraints = @UniqueConstraint(columnNames = { "locale" })) @Table(name = "i18n", uniqueConstraints = @UniqueConstraint(columnNames = { "locale" }))
public class I18n { public class I18n {
@Id @Id
@Column(name = "locale", unique = true, nullable = false) @Column(name = "locale", unique = true, nullable = false)
private String locale; private String locale;
@Lob @Lob
@Column(name = "label") @Column(name = "label")
private String label; private String label;

View File

@ -13,7 +13,6 @@ import de.bstly.board.i18n.model.I18n;
* The Interface I18nRepository. * The Interface I18nRepository.
*/ */
@Repository @Repository
public interface I18nRepository public interface I18nRepository extends JpaRepository<I18n, String>, QuerydslPredicateExecutor<I18n> {
extends JpaRepository<I18n, String>, QuerydslPredicateExecutor<I18n> {
} }

View File

@ -217,6 +217,8 @@ public class Comment {
} }
/** /**
* Gets the type.
*
* @return the type * @return the type
*/ */
public Types getType() { public Types getType() {

View File

@ -327,6 +327,8 @@ public class Entry {
} }
/** /**
* Gets the type.
*
* @return the type * @return the type
*/ */
public Types getType() { public Types getType() {

View File

@ -247,6 +247,8 @@ public class LocalUser {
} }
/** /**
* Gets the type.
*
* @return the type * @return the type
*/ */
public Types getType() { public Types getType() {

View File

@ -41,7 +41,7 @@ public class Tag implements Serializable {
/** /**
* Instantiates a new tag. * Instantiates a new tag.
* *
* @param tag the tag * @param tag the tag
* @param target the target * @param target the target
*/ */
public Tag(String tag, Long target) { public Tag(String tag, Long target) {

View File

@ -133,6 +133,8 @@ public class View {
} }
/** /**
* Gets the index.
*
* @return the index * @return the index
*/ */
public int getIndex() { public int getIndex() {
@ -140,7 +142,9 @@ public class View {
} }
/** /**
* @param index the index to set * Sets the index.
*
* @param index the new index
*/ */
public void setIndex(int index) { public void setIndex(int index) {
this.index = index; this.index = index;
@ -201,28 +205,36 @@ public class View {
} }
/** /**
* @return the publicView * Checks if is public view.
*
* @return true, if is public view
*/ */
public boolean isPublicView() { public boolean isPublicView() {
return publicView; return publicView;
} }
/** /**
* @param publicView the publicView to set * Sets the public view.
*
* @param publicView the new public view
*/ */
public void setPublicView(boolean publicView) { public void setPublicView(boolean publicView) {
this.publicView = publicView; this.publicView = publicView;
} }
/** /**
* @return the divider * Checks if is divider.
*
* @return true, if is divider
*/ */
public boolean isDivider() { public boolean isDivider() {
return divider; return divider;
} }
/** /**
* @param divider the divider to set * Sets the divider.
*
* @param divider the new divider
*/ */
public void setDivider(boolean divider) { public void setDivider(boolean divider) {
this.divider = divider; this.divider = divider;

View File

@ -16,7 +16,6 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import de.bstly.board.model.support.Types; import de.bstly.board.model.support.Types;
import de.bstly.board.model.support.VoteType; import de.bstly.board.model.support.VoteType;
/** /**
* The Class Vote. * The Class Vote.
*/ */
@ -24,7 +23,7 @@ import de.bstly.board.model.support.VoteType;
@Table(name = "votes") @Table(name = "votes")
@EntityListeners({ AuditingEntityListener.class }) @EntityListeners({ AuditingEntityListener.class })
public class Vote { public class Vote {
@Id @Id
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id") @Column(name = "id")

View File

@ -15,7 +15,10 @@ import org.hibernate.search.mapper.pojo.bridge.runtime.ValueBridgeToIndexedValue
public class InstantValueBridge implements ValueBridge<Instant, String> { public class InstantValueBridge implements ValueBridge<Instant, String> {
/* /*
* @see org.hibernate.search.mapper.pojo.bridge.ValueBridge#toIndexedValue(java.lang.Object, org.hibernate.search.mapper.pojo.bridge.runtime.ValueBridgeToIndexedValueContext) * @see
* org.hibernate.search.mapper.pojo.bridge.ValueBridge#toIndexedValue(java.lang.
* Object, org.hibernate.search.mapper.pojo.bridge.runtime.
* ValueBridgeToIndexedValueContext)
*/ */
@Override @Override
public String toIndexedValue(Instant value, ValueBridgeToIndexedValueContext context) { public String toIndexedValue(Instant value, ValueBridgeToIndexedValueContext context) {
@ -23,7 +26,10 @@ public class InstantValueBridge implements ValueBridge<Instant, String> {
} }
/* /*
* @see org.hibernate.search.mapper.pojo.bridge.ValueBridge#fromIndexedValue(java.lang.Object, org.hibernate.search.mapper.pojo.bridge.runtime.ValueBridgeFromIndexedValueContext) * @see
* org.hibernate.search.mapper.pojo.bridge.ValueBridge#fromIndexedValue(java.
* lang.Object, org.hibernate.search.mapper.pojo.bridge.runtime.
* ValueBridgeFromIndexedValueContext)
*/ */
@Override @Override
public Instant fromIndexedValue(String value, ValueBridgeFromIndexedValueContext context) { public Instant fromIndexedValue(String value, ValueBridgeFromIndexedValueContext context) {

View File

@ -13,7 +13,6 @@ import de.bstly.board.model.Bookmarks;
* The Interface BookmarksRepository. * The Interface BookmarksRepository.
*/ */
@Repository @Repository
public interface BookmarksRepository public interface BookmarksRepository extends JpaRepository<Bookmarks, String>, QuerydslPredicateExecutor<Bookmarks> {
extends JpaRepository<Bookmarks, String>, QuerydslPredicateExecutor<Bookmarks> {
} }

View File

@ -13,6 +13,5 @@ import de.bstly.board.model.Comment;
* The Interface CommentRepository. * The Interface CommentRepository.
*/ */
@Repository @Repository
public interface CommentRepository public interface CommentRepository extends JpaRepository<Comment, Long>, QuerydslPredicateExecutor<Comment> {
extends JpaRepository<Comment, Long>, QuerydslPredicateExecutor<Comment> {
} }

View File

@ -13,7 +13,6 @@ import de.bstly.board.model.Entry;
* The Interface EntryRepository. * The Interface EntryRepository.
*/ */
@Repository @Repository
public interface EntryRepository public interface EntryRepository extends JpaRepository<Entry, Long>, QuerydslPredicateExecutor<Entry> {
extends JpaRepository<Entry, Long>, QuerydslPredicateExecutor<Entry> {
} }

View File

@ -13,7 +13,6 @@ import de.bstly.board.model.LocalUser;
* The Interface LocalUserRepository. * The Interface LocalUserRepository.
*/ */
@Repository @Repository
public interface LocalUserRepository public interface LocalUserRepository extends JpaRepository<LocalUser, String>, QuerydslPredicateExecutor<LocalUser> {
extends JpaRepository<LocalUser, String>, QuerydslPredicateExecutor<LocalUser> {
} }

View File

@ -13,7 +13,6 @@ import de.bstly.board.model.View;
* The Interface ViewRepository. * The Interface ViewRepository.
*/ */
@Repository @Repository
public interface ViewRepository public interface ViewRepository extends JpaRepository<View, Long>, QuerydslPredicateExecutor<View> {
extends JpaRepository<View, Long>, QuerydslPredicateExecutor<View> {
} }

View File

@ -9,7 +9,6 @@ import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices; import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository; import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
/** /**
* The Class LocalRememberMeServices. * The Class LocalRememberMeServices.
*/ */
@ -18,18 +17,19 @@ public class LocalRememberMeServices extends PersistentTokenBasedRememberMeServi
/** /**
* Instantiates a new local remember me services. * Instantiates a new local remember me services.
* *
* @param key the key * @param key the key
* @param userDetailsService the user details service * @param userDetailsService the user details service
* @param tokenRepository the token repository * @param tokenRepository the token repository
*/ */
public LocalRememberMeServices(String key, UserDetailsService userDetailsService, public LocalRememberMeServices(String key, UserDetailsService userDetailsService,
PersistentTokenRepository tokenRepository) { PersistentTokenRepository tokenRepository) {
super(key, userDetailsService, tokenRepository); super(key, userDetailsService, tokenRepository);
} }
/* /*
* @see org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices#rememberMeRequested(javax.servlet.http.HttpServletRequest, java.lang.String) * @see org.springframework.security.web.authentication.rememberme.
* AbstractRememberMeServices#rememberMeRequested(javax.servlet.http.
* HttpServletRequest, java.lang.String)
*/ */
@Override @Override
protected boolean rememberMeRequested(HttpServletRequest request, String parameter) { protected boolean rememberMeRequested(HttpServletRequest request, String parameter) {

View File

@ -21,12 +21,11 @@ public class LocalUserDetails extends User {
/** /**
* Instantiates a new local user details. * Instantiates a new local user details.
* *
* @param username the username * @param username the username
* @param password the password * @param password the password
* @param authorities the authorities * @param authorities the authorities
*/ */
public LocalUserDetails(String username, String password, public LocalUserDetails(String username, String password, Collection<? extends GrantedAuthority> authorities) {
Collection<? extends GrantedAuthority> authorities) {
super(username, password, authorities); super(username, password, authorities);
} }

View File

@ -29,17 +29,18 @@ import de.bstly.board.model.LocalUser;
* The Class OAuth2AuthenticationSuccessHandler. * The Class OAuth2AuthenticationSuccessHandler.
*/ */
@Component @Component
public class OAuth2AuthenticationSuccessHandler public class OAuth2AuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
extends SavedRequestAwareAuthenticationSuccessHandler {
@Autowired @Autowired
private UserManager localUserManager; private UserManager localUserManager;
private RememberMeServices rememberMeServices; private RememberMeServices rememberMeServices;
/* /*
* @see org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler#onAuthenticationSuccess(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.Authentication) * @see org.springframework.security.web.authentication.
* SavedRequestAwareAuthenticationSuccessHandler#onAuthenticationSuccess(javax.
* servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
* org.springframework.security.core.Authentication)
*/ */
@Override @Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
@ -52,8 +53,8 @@ public class OAuth2AuthenticationSuccessHandler
authorities.addAll(authentication.getAuthorities()); authorities.addAll(authentication.getAuthorities());
authorities.addAll(userDetails.getAuthorities()); authorities.addAll(userDetails.getAuthorities());
UsernamePasswordAuthenticationToken newAuthentication = new UsernamePasswordAuthenticationToken( UsernamePasswordAuthenticationToken newAuthentication = new UsernamePasswordAuthenticationToken(userDetails,
userDetails, null, authorities); null, authorities);
SecurityContextHolder.getContext().setAuthentication(newAuthentication); SecurityContextHolder.getContext().setAuthentication(newAuthentication);

View File

@ -51,7 +51,9 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
private String loginTargetUrl; private String loginTargetUrl;
/* /*
* @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#configure(org.springframework.security.config.annotation.web.builders.HttpSecurity) * @see org.springframework.security.config.annotation.web.configuration.
* WebSecurityConfigurerAdapter#configure(org.springframework.security.config.
* annotation.web.builders.HttpSecurity)
*/ */
/* /*
* @see org.springframework.security.config.annotation.web.configuration. * @see org.springframework.security.config.annotation.web.configuration.
@ -73,25 +75,20 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
.anonymous().disable() .anonymous().disable()
// login // login
.formLogin().loginPage("/login").defaultSuccessUrl(loginTargetUrl) .formLogin().loginPage("/login").defaultSuccessUrl(loginTargetUrl)
.failureHandler(new SimpleUrlAuthenticationFailureHandler(loginUrl .failureHandler(new SimpleUrlAuthenticationFailureHandler(loginUrl + "?error")).and()
+ "?error"))
.and()
// remember me // remember me
.rememberMe().rememberMeServices(rememberMeServices()).and() .rememberMe().rememberMeServices(rememberMeServices()).and()
// logout // logout
.logout().logoutUrl("/logout") .logout().logoutUrl("/logout")
.logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK)) .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK)).and()
.and()
// exception // exception
.exceptionHandling() .exceptionHandling()
.defaultAuthenticationEntryPointFor( .defaultAuthenticationEntryPointFor(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED),
new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED),
new AntPathRequestMatcher("/api/**")) new AntPathRequestMatcher("/api/**"))
.and() .and()
// oidc // oidc
.oauth2Login().successHandler(oAuth2AuthenticationSuccessHandler) .oauth2Login().successHandler(oAuth2AuthenticationSuccessHandler)
.failureHandler(new SimpleUrlAuthenticationFailureHandler(loginUrl .failureHandler(new SimpleUrlAuthenticationFailureHandler(loginUrl + "?externalError"))
+ "?externalError"))
.loginPage("/login"); .loginPage("/login");
} }
@ -124,8 +121,8 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
*/ */
@Bean @Bean
public RememberMeServices rememberMeServices() { public RememberMeServices rememberMeServices() {
PersistentTokenBasedRememberMeServices rememberMeServices = new LocalRememberMeServices( PersistentTokenBasedRememberMeServices rememberMeServices = new LocalRememberMeServices("remember-me",
"remember-me", localUserManager, persistentTokenRepository()); localUserManager, persistentTokenRepository());
return rememberMeServices; return rememberMeServices;
} }