apply intellij fixes

This commit is contained in:
Athou
2023-12-27 08:52:24 +01:00
parent 1b4b3ca52c
commit 9cd1cde571
43 changed files with 151 additions and 190 deletions

View File

@@ -80,7 +80,7 @@ export function Subscribe() {
> >
<TextInput <TextInput
label={<Trans>Feed URL</Trans>} label={<Trans>Feed URL</Trans>}
placeholder="http://www.mysite.com/rss" placeholder="https://www.mysite.com/rss"
description={ description={
<Trans> <Trans>
The URL for the feed you want to subscribe to. You can also use the website's url directly and CommaFeed The URL for the feed you want to subscribe to. You can also use the website's url directly and CommaFeed

View File

@@ -38,7 +38,7 @@ function FilteringExpressionDescription() {
<div> <div>
<Trans> <Trans>
<span>Complete syntax is available </span> <span>Complete syntax is available </span>
<a href="http://commons.apache.org/proper/commons-jexl/reference/syntax.html" target="_blank" rel="noreferrer"> <a href="https://commons.apache.org/proper/commons-jexl/reference/syntax.html" target="_blank" rel="noreferrer">
here here
</a> </a>
. .

View File

@@ -88,30 +88,14 @@ public class CommaFeedApplication extends Application<CommaFeedConfiguration> {
@Override @Override
public void initialize(Bootstrap<CommaFeedConfiguration> bootstrap) { public void initialize(Bootstrap<CommaFeedConfiguration> bootstrap) {
bootstrap.setConfigurationFactoryFactory(new DefaultConfigurationFactoryFactory<CommaFeedConfiguration>() { configureEnvironmentSubstitutor(bootstrap);
@Override
protected ObjectMapper configureObjectMapper(ObjectMapper objectMapper) {
// disable case sensitivity because EnvironmentSubstitutor maps MYPROPERTY to myproperty and not to myProperty
return objectMapper
.setConfig(objectMapper.getDeserializationConfig().with(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES));
}
});
// enable config.yml string substitution
// e.g. having a custom config.yml file with app.session.path=${SOME_ENV_VAR} will substitute SOME_ENV_VAR
SubstitutingSourceProvider substitutingSourceProvider = new SubstitutingSourceProvider(bootstrap.getConfigurationSourceProvider(),
new EnvironmentVariableSubstitutor(false));
// enable config.yml properties override with env variables prefixed with CF_
// e.g. setting CF_APP_ALLOWREGISTRATIONS=true will set app.allowRegistrations to true
EnvironmentSubstitutor environmentSubstitutor = new EnvironmentSubstitutor("CF", substitutingSourceProvider);
bootstrap.setConfigurationSourceProvider(environmentSubstitutor);
bootstrap.getObjectMapper().registerModule(new MetricsModule(TimeUnit.SECONDS, TimeUnit.SECONDS, false)); bootstrap.getObjectMapper().registerModule(new MetricsModule(TimeUnit.SECONDS, TimeUnit.SECONDS, false));
bootstrap.addBundle(websocketBundle = new WebsocketBundle<>()); bootstrap.addBundle(websocketBundle = new WebsocketBundle<>());
bootstrap.addBundle(hibernateBundle = new HibernateBundle<CommaFeedConfiguration>(AbstractModel.class, Feed.class, bootstrap.addBundle(hibernateBundle = new HibernateBundle<>(AbstractModel.class, Feed.class, FeedCategory.class, FeedEntry.class,
FeedCategory.class, FeedEntry.class, FeedEntryContent.class, FeedEntryStatus.class, FeedEntryTag.class, FeedEntryContent.class, FeedEntryStatus.class, FeedEntryTag.class, FeedSubscription.class, User.class, UserRole.class,
FeedSubscription.class, User.class, UserRole.class, UserSettings.class) { UserSettings.class) {
@Override @Override
public DataSourceFactory getDataSourceFactory(CommaFeedConfiguration configuration) { public DataSourceFactory getDataSourceFactory(CommaFeedConfiguration configuration) {
DataSourceFactory factory = configuration.getDataSourceFactory(); DataSourceFactory factory = configuration.getDataSourceFactory();
@@ -126,7 +110,7 @@ public class CommaFeedApplication extends Application<CommaFeedConfiguration> {
} }
}); });
bootstrap.addBundle(new MigrationsBundle<CommaFeedConfiguration>() { bootstrap.addBundle(new MigrationsBundle<>() {
@Override @Override
public DataSourceFactory getDataSourceFactory(CommaFeedConfiguration configuration) { public DataSourceFactory getDataSourceFactory(CommaFeedConfiguration configuration) {
return configuration.getDataSourceFactory(); return configuration.getDataSourceFactory();
@@ -137,8 +121,32 @@ public class CommaFeedApplication extends Application<CommaFeedConfiguration> {
bootstrap.addBundle(new MultiPartBundle()); bootstrap.addBundle(new MultiPartBundle());
} }
private static void configureEnvironmentSubstitutor(Bootstrap<CommaFeedConfiguration> bootstrap) {
bootstrap.setConfigurationFactoryFactory(new DefaultConfigurationFactoryFactory<>() {
@Override
protected ObjectMapper configureObjectMapper(ObjectMapper objectMapper) {
// disable case sensitivity because EnvironmentSubstitutor maps MYPROPERTY to myproperty and not to myProperty
return objectMapper
.setConfig(objectMapper.getDeserializationConfig().with(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES));
}
});
bootstrap.setConfigurationSourceProvider(buildEnvironmentSubstitutor(bootstrap));
}
private static EnvironmentSubstitutor buildEnvironmentSubstitutor(Bootstrap<CommaFeedConfiguration> bootstrap) {
// enable config.yml string substitution
// e.g. having a custom config.yml file with app.session.path=${SOME_ENV_VAR} will substitute SOME_ENV_VAR
SubstitutingSourceProvider substitutingSourceProvider = new SubstitutingSourceProvider(bootstrap.getConfigurationSourceProvider(),
new EnvironmentVariableSubstitutor(false));
// enable config.yml properties override with env variables prefixed with CF_
// e.g. setting CF_APP_ALLOWREGISTRATIONS=true will set app.allowRegistrations to true
return new EnvironmentSubstitutor("CF", substitutingSourceProvider);
}
@Override @Override
public void run(CommaFeedConfiguration config, Environment environment) throws Exception { public void run(CommaFeedConfiguration config, Environment environment) {
PasswordConstraintValidator.setStrict(config.getApplicationSettings().getStrictPasswordPolicy()); PasswordConstraintValidator.setStrict(config.getApplicationSettings().getStrictPasswordPolicy());
// guice init // guice init
@@ -180,7 +188,7 @@ public class CommaFeedApplication extends Application<CommaFeedConfiguration> {
websocketBundle.addEndpoint(serverEndpointConfig); websocketBundle.addEndpoint(serverEndpointConfig);
// Scheduled tasks // Scheduled tasks
Set<ScheduledTask> tasks = injector.getInstance(Key.get(new TypeLiteral<Set<ScheduledTask>>() { Set<ScheduledTask> tasks = injector.getInstance(Key.get(new TypeLiteral<>() {
})); }));
ScheduledExecutorService executor = environment.lifecycle() ScheduledExecutorService executor = environment.lifecycle()
.scheduledExecutorService("task-scheduler", true) .scheduledExecutorService("task-scheduler", true)

View File

@@ -18,7 +18,7 @@ public class FixedSizeSortedSet<E> {
private final int capacity; private final int capacity;
public FixedSizeSortedSet(int capacity, Comparator<? super E> comparator) { public FixedSizeSortedSet(int capacity, Comparator<? super E> comparator) {
this.inner = new ArrayList<E>(Math.max(0, capacity)); this.inner = new ArrayList<>(Math.max(0, capacity));
this.capacity = capacity < 0 ? Integer.MAX_VALUE : capacity; this.capacity = capacity < 0 ? Integer.MAX_VALUE : capacity;
this.comparator = comparator; this.comparator = comparator;
} }

View File

@@ -34,9 +34,7 @@ public class RedisCacheService extends CacheService {
try (Jedis jedis = pool.getResource()) { try (Jedis jedis = pool.getResource()) {
String key = buildRedisEntryKey(feed); String key = buildRedisEntryKey(feed);
Set<String> members = jedis.smembers(key); Set<String> members = jedis.smembers(key);
for (String member : members) { list.addAll(members);
list.add(member);
}
} }
return list; return list;
} }

View File

@@ -2,7 +2,6 @@ package com.commafeed.backend.dao;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.stream.Collectors;
import org.hibernate.SessionFactory; import org.hibernate.SessionFactory;
@@ -34,7 +33,7 @@ public class FeedCategoryDAO extends GenericDAO<FeedCategory> {
} }
public FeedCategory findByName(User user, String name, FeedCategory parent) { public FeedCategory findByName(User user, String name, FeedCategory parent) {
Predicate parentPredicate = null; Predicate parentPredicate;
if (parent == null) { if (parent == null) {
parentPredicate = category.parent.isNull(); parentPredicate = category.parent.isNull();
} else { } else {
@@ -44,7 +43,7 @@ public class FeedCategoryDAO extends GenericDAO<FeedCategory> {
} }
public List<FeedCategory> findByParent(User user, FeedCategory parent) { public List<FeedCategory> findByParent(User user, FeedCategory parent) {
Predicate parentPredicate = null; Predicate parentPredicate;
if (parent == null) { if (parent == null) {
parentPredicate = category.parent.isNull(); parentPredicate = category.parent.isNull();
} else { } else {
@@ -54,7 +53,7 @@ public class FeedCategoryDAO extends GenericDAO<FeedCategory> {
} }
public List<FeedCategory> findAllChildrenCategories(User user, FeedCategory parent) { public List<FeedCategory> findAllChildrenCategories(User user, FeedCategory parent) {
return findAll(user).stream().filter(c -> isChild(c, parent)).collect(Collectors.toList()); return findAll(user).stream().filter(c -> isChild(c, parent)).toList();
} }
private boolean isChild(FeedCategory child, FeedCategory parent) { private boolean isChild(FeedCategory child, FeedCategory parent) {

View File

@@ -1,7 +1,6 @@
package com.commafeed.backend.dao; package com.commafeed.backend.dao;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.codec.digest.DigestUtils;
import org.hibernate.SessionFactory; import org.hibernate.SessionFactory;
@@ -43,7 +42,7 @@ public class FeedEntryDAO extends GenericDAO<FeedEntry> {
.having(count.gt(maxCapacity)) .having(count.gt(maxCapacity))
.limit(max) .limit(max)
.fetch(); .fetch();
return tuples.stream().map(t -> new FeedCapacity(t.get(entry.feed.id), t.get(count))).collect(Collectors.toList()); return tuples.stream().map(t -> new FeedCapacity(t.get(entry.feed.id), t.get(count))).toList();
} }
public int delete(Long feedId, long max) { public int delete(Long feedId, long max) {

View File

@@ -38,14 +38,11 @@ import jakarta.inject.Singleton;
@Singleton @Singleton
public class FeedEntryStatusDAO extends GenericDAO<FeedEntryStatus> { public class FeedEntryStatusDAO extends GenericDAO<FeedEntryStatus> {
private static final Comparator<FeedEntryStatus> STATUS_COMPARATOR_DESC = new Comparator<FeedEntryStatus>() { private static final Comparator<FeedEntryStatus> STATUS_COMPARATOR_DESC = (o1, o2) -> {
@Override CompareToBuilder builder = new CompareToBuilder();
public int compare(FeedEntryStatus o1, FeedEntryStatus o2) { builder.append(o2.getEntryUpdated(), o1.getEntryUpdated());
CompareToBuilder builder = new CompareToBuilder(); builder.append(o2.getId(), o1.getId());
builder.append(o2.getEntryUpdated(), o1.getEntryUpdated()); return builder.toComparison();
builder.append(o2.getId(), o1.getId());
return builder.toComparison();
}
}; };
private static final Comparator<FeedEntryStatus> STATUS_COMPARATOR_ASC = Ordering.from(STATUS_COMPARATOR_DESC).reverse(); private static final Comparator<FeedEntryStatus> STATUS_COMPARATOR_ASC = Ordering.from(STATUS_COMPARATOR_DESC).reverse();
@@ -239,7 +236,7 @@ public class FeedEntryStatusDAO extends GenericDAO<FeedEntryStatus> {
} }
placeholders = placeholders.subList(Math.max(offset, 0), size); placeholders = placeholders.subList(Math.max(offset, 0), size);
List<FeedEntryStatus> statuses = null; List<FeedEntryStatus> statuses;
if (onlyIds) { if (onlyIds) {
statuses = placeholders; statuses = placeholders;
} else { } else {
@@ -264,7 +261,7 @@ public class FeedEntryStatusDAO extends GenericDAO<FeedEntryStatus> {
for (Tuple tuple : tuples) { for (Tuple tuple : tuples) {
Long count = tuple.get(entry.count()); Long count = tuple.get(entry.count());
Date updated = tuple.get(entry.updated.max()); Date updated = tuple.get(entry.updated.max());
uc = new UnreadCount(subscription.getId(), count, updated); uc = new UnreadCount(subscription.getId(), count == null ? 0 : count, updated);
} }
return uc; return uc;
} }

View File

@@ -6,6 +6,7 @@ import java.util.stream.Collectors;
import org.hibernate.SessionFactory; import org.hibernate.SessionFactory;
import com.commafeed.backend.model.AbstractModel;
import com.commafeed.backend.model.Feed; import com.commafeed.backend.model.Feed;
import com.commafeed.backend.model.FeedCategory; import com.commafeed.backend.model.FeedCategory;
import com.commafeed.backend.model.FeedSubscription; import com.commafeed.backend.model.FeedSubscription;
@@ -74,14 +75,12 @@ public class FeedSubscriptionDAO extends GenericDAO<FeedSubscription> {
} }
public List<FeedSubscription> findByCategories(User user, List<FeedCategory> categories) { public List<FeedSubscription> findByCategories(User user, List<FeedCategory> categories) {
Set<Long> categoryIds = categories.stream().map(c -> c.getId()).collect(Collectors.toSet()); Set<Long> categoryIds = categories.stream().map(AbstractModel::getId).collect(Collectors.toSet());
return findAll(user).stream() return findAll(user).stream().filter(s -> s.getCategory() != null && categoryIds.contains(s.getCategory().getId())).toList();
.filter(s -> s.getCategory() != null && categoryIds.contains(s.getCategory().getId()))
.collect(Collectors.toList());
} }
private List<FeedSubscription> initRelations(List<FeedSubscription> list) { private List<FeedSubscription> initRelations(List<FeedSubscription> list) {
list.forEach(s -> initRelations(s)); list.forEach(this::initRelations);
return list; return list;
} }

View File

@@ -58,7 +58,7 @@ public abstract class GenericDAO<T extends AbstractModel> extends AbstractDAO<T>
} }
public int delete(Collection<T> objects) { public int delete(Collection<T> objects) {
objects.forEach(o -> delete(o)); objects.forEach(this::delete);
return objects.size(); return objects.size();
} }

View File

@@ -33,6 +33,6 @@ public class UserRoleDAO extends GenericDAO<UserRole> {
} }
public Set<Role> findRoles(User user) { public Set<Role> findRoles(User user) {
return findAll(user).stream().map(r -> r.getRole()).collect(Collectors.toSet()); return findAll(user).stream().map(UserRole::getRole).collect(Collectors.toSet());
} }
} }

View File

@@ -84,7 +84,7 @@ public class DefaultFaviconFetcher extends AbstractFaviconFetcher {
private Favicon getIconInPage(String url) { private Favicon getIconInPage(String url) {
Document doc = null; Document doc;
try { try {
HttpResult result = getter.getBinary(url, TIMEOUT); HttpResult result = getter.getBinary(url, TIMEOUT);
doc = Jsoup.parse(new String(result.getContent()), url); doc = Jsoup.parse(new String(result.getContent()), url);
@@ -109,8 +109,8 @@ public class DefaultFaviconFetcher extends AbstractFaviconFetcher {
log.debug("Found unconfirmed iconInPage at {}", href); log.debug("Found unconfirmed iconInPage at {}", href);
byte[] bytes = null; byte[] bytes;
String contentType = null; String contentType;
try { try {
HttpResult result = getter.getBinary(href, TIMEOUT); HttpResult result = getter.getBinary(href, TIMEOUT);
bytes = result.getContent(); bytes = result.getContent();

View File

@@ -58,7 +58,7 @@ public class FacebookFaviconFetcher extends AbstractFaviconFetcher {
} }
private String extractUserName(String url) { private String extractUserName(String url) {
URI uri = null; URI uri;
try { try {
uri = new URI(url); uri = new URI(url);
} catch (URISyntaxException e) { } catch (URISyntaxException e) {

View File

@@ -36,7 +36,7 @@ public class FeedFetcher {
private final Set<FeedURLProvider> urlProviders; private final Set<FeedURLProvider> urlProviders;
public FeedFetcherResult fetch(String feedUrl, boolean extractFeedUrlFromHtml, String lastModified, String eTag, Date lastPublishedDate, public FeedFetcherResult fetch(String feedUrl, boolean extractFeedUrlFromHtml, String lastModified, String eTag, Date lastPublishedDate,
String lastContentHash) throws FeedException, IOException, NotModifiedException, InterruptedException { String lastContentHash) throws FeedException, IOException, NotModifiedException {
log.debug("Fetching feed {}", feedUrl); log.debug("Fetching feed {}", feedUrl);
int timeout = 20000; int timeout = 20000;

View File

@@ -184,7 +184,7 @@ public class FeedParser {
} }
private String getContent(SyndEntry item) { private String getContent(SyndEntry item) {
String content = null; String content;
if (item.getContents().isEmpty()) { if (item.getContents().isEmpty()) {
content = item.getDescription() == null ? null : item.getDescription().getValue(); content = item.getDescription() == null ? null : item.getDescription().getValue();
} else { } else {

View File

@@ -10,7 +10,6 @@ import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.SynchronousQueue; import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.apache.commons.lang3.time.DateUtils; import org.apache.commons.lang3.time.DateUtils;
@@ -173,7 +172,7 @@ public class FeedRefreshEngine implements Managed {
List<Feed> feeds = feedDAO.findNextUpdatable(max, lastLoginThreshold); List<Feed> feeds = feedDAO.findNextUpdatable(max, lastLoginThreshold);
// update disabledUntil to prevent feeds from being returned again by feedDAO.findNextUpdatable() // update disabledUntil to prevent feeds from being returned again by feedDAO.findNextUpdatable()
Date nextUpdateDate = DateUtils.addMinutes(new Date(), config.getApplicationSettings().getRefreshIntervalMinutes()); Date nextUpdateDate = DateUtils.addMinutes(new Date(), config.getApplicationSettings().getRefreshIntervalMinutes());
feedDAO.setDisabledUntil(feeds.stream().map(AbstractModel::getId).collect(Collectors.toList()), nextUpdateDate); feedDAO.setDisabledUntil(feeds.stream().map(AbstractModel::getId).toList(), nextUpdateDate);
return feeds; return feeds;
}); });
} }

View File

@@ -7,7 +7,6 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.Lock;
import java.util.stream.Collectors;
import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
@@ -150,7 +149,7 @@ public class FeedRefreshUpdater implements Managed {
if (subscriptions == null) { if (subscriptions == null) {
feed.setMessage("No new entries found"); feed.setMessage("No new entries found");
} else if (insertedAtLeastOneEntry) { } else if (insertedAtLeastOneEntry) {
List<User> users = subscriptions.stream().map(FeedSubscription::getUser).collect(Collectors.toList()); List<User> users = subscriptions.stream().map(FeedSubscription::getUser).toList();
cache.invalidateUnreadCount(subscriptions.toArray(new FeedSubscription[0])); cache.invalidateUnreadCount(subscriptions.toArray(new FeedSubscription[0]));
cache.invalidateUserRootCategory(users.toArray(new User[0])); cache.invalidateUserRootCategory(users.toArray(new User[0]));

View File

@@ -3,7 +3,6 @@ package com.commafeed.backend.feed;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
@@ -52,7 +51,7 @@ public class FeedRefreshWorker {
Integer maxFeedCapacity = config.getApplicationSettings().getMaxFeedCapacity(); Integer maxFeedCapacity = config.getApplicationSettings().getMaxFeedCapacity();
if (maxFeedCapacity > 0) { if (maxFeedCapacity > 0) {
entries = entries.stream().limit(maxFeedCapacity).collect(Collectors.toList()); entries = entries.stream().limit(maxFeedCapacity).toList();
} }
String urlAfterRedirect = feedFetcherResult.getUrlAfterRedirect(); String urlAfterRedirect = feedFetcherResult.getUrlAfterRedirect();

View File

@@ -8,7 +8,6 @@ import java.util.Collections;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.ahocorasick.trie.Emit; import org.ahocorasick.trie.Emit;
import org.ahocorasick.trie.Trie; import org.ahocorasick.trie.Trie;
@@ -246,7 +245,7 @@ public class FeedUtils {
} }
public static List<Long> getSortedTimestamps(List<FeedEntry> entries) { public static List<Long> getSortedTimestamps(List<FeedEntry> entries) {
return entries.stream().map(t -> t.getUpdated().getTime()).sorted(Collections.reverseOrder()).collect(Collectors.toList()); return entries.stream().map(t -> t.getUpdated().getTime()).sorted(Collections.reverseOrder()).toList();
} }
public static String removeTrailingSlash(String url) { public static String removeTrailingSlash(String url) {
@@ -278,7 +277,7 @@ public class FeedUtils {
return url; return url;
} }
String result = null; String result;
try { try {
result = new URL(new URL(baseUrl), url).toString(); result = new URL(new URL(baseUrl), url).toString();
} catch (MalformedURLException e) { } catch (MalformedURLException e) {
@@ -307,7 +306,7 @@ public class FeedUtils {
Elements elements = doc.select("img"); Elements elements = doc.select("img");
for (Element element : elements) { for (Element element : elements) {
String href = element.attr("src"); String href = element.attr("src");
if (href != null) { if (StringUtils.isNotBlank(href)) {
String proxy = proxyImage(href); String proxy = proxyImage(href);
element.attr("src", proxy); element.attr("src", proxy);
} }

View File

@@ -263,7 +263,7 @@ public class HtmlEntities {
map.put("&zwnj;", "&#8204;"); map.put("&zwnj;", "&#8204;");
HTML_TO_NUMERIC_MAP = Collections.unmodifiableMap(map); HTML_TO_NUMERIC_MAP = Collections.unmodifiableMap(map);
HTML_ENTITIES = map.keySet().toArray(new String[map.size()]); HTML_ENTITIES = map.keySet().toArray(new String[0]);
NUMERIC_ENTITIES = map.values().toArray(new String[map.size()]); NUMERIC_ENTITIES = map.values().toArray(new String[0]);
} }
} }

View File

@@ -1,9 +1,8 @@
package com.commafeed.backend.opml; package com.commafeed.backend.opml;
import java.util.Collections; import java.util.Comparator;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.ObjectUtils;
@@ -34,20 +33,18 @@ public class OPMLExporter {
opml.setCreated(new Date()); opml.setCreated(new Date());
List<FeedCategory> categories = feedCategoryDAO.findAll(user); List<FeedCategory> categories = feedCategoryDAO.findAll(user);
Collections.sort(categories, categories.sort(Comparator.comparingInt(e -> ObjectUtils.firstNonNull(e.getPosition(), 0)));
(e1, e2) -> ObjectUtils.firstNonNull(e1.getPosition(), 0) - ObjectUtils.firstNonNull(e2.getPosition(), 0));
List<FeedSubscription> subscriptions = feedSubscriptionDAO.findAll(user); List<FeedSubscription> subscriptions = feedSubscriptionDAO.findAll(user);
Collections.sort(subscriptions, subscriptions.sort(Comparator.comparingInt(e -> ObjectUtils.firstNonNull(e.getPosition(), 0)));
(e1, e2) -> ObjectUtils.firstNonNull(e1.getPosition(), 0) - ObjectUtils.firstNonNull(e2.getPosition(), 0));
// export root categories // export root categories
for (FeedCategory cat : categories.stream().filter(c -> c.getParent() == null).collect(Collectors.toList())) { for (FeedCategory cat : categories.stream().filter(c -> c.getParent() == null).toList()) {
opml.getOutlines().add(buildCategoryOutline(cat, categories, subscriptions)); opml.getOutlines().add(buildCategoryOutline(cat, categories, subscriptions));
} }
// export root subscriptions // export root subscriptions
for (FeedSubscription sub : subscriptions.stream().filter(s -> s.getCategory() == null).collect(Collectors.toList())) { for (FeedSubscription sub : subscriptions.stream().filter(s -> s.getCategory() == null).toList()) {
opml.getOutlines().add(buildSubscriptionOutline(sub)); opml.getOutlines().add(buildSubscriptionOutline(sub));
} }
@@ -62,13 +59,13 @@ public class OPMLExporter {
for (FeedCategory child : categories.stream() for (FeedCategory child : categories.stream()
.filter(c -> c.getParent() != null && c.getParent().getId().equals(cat.getId())) .filter(c -> c.getParent() != null && c.getParent().getId().equals(cat.getId()))
.collect(Collectors.toList())) { .toList()) {
outline.getChildren().add(buildCategoryOutline(child, categories, subscriptions)); outline.getChildren().add(buildCategoryOutline(child, categories, subscriptions));
} }
for (FeedSubscription sub : subscriptions.stream() for (FeedSubscription sub : subscriptions.stream()
.filter(s -> s.getCategory() != null && s.getCategory().getId().equals(cat.getId())) .filter(s -> s.getCategory() != null && s.getCategory().getId().equals(cat.getId()))
.collect(Collectors.toList())) { .toList()) {
outline.getChildren().add(buildSubscriptionOutline(sub)); outline.getChildren().add(buildSubscriptionOutline(sub));
} }
return outline; return outline;

View File

@@ -21,7 +21,7 @@ public class RSSRDF10Parser extends RSS10Parser {
@Override @Override
public boolean isMyType(Document document) { public boolean isMyType(Document document) {
boolean ok = false; boolean ok;
Element rssRoot = document.getRootElement(); Element rssRoot = document.getRootElement();
Namespace defaultNS = rssRoot.getNamespace(); Namespace defaultNS = rssRoot.getNamespace();

View File

@@ -41,7 +41,7 @@ public class FeedEntryFilteringService {
// classloader that prevents object creation // classloader that prevents object creation
ClassLoader cl = new ClassLoader() { ClassLoader cl = new ClassLoader() {
@Override @Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { protected Class<?> loadClass(String name, boolean resolve) {
return null; return null;
} }
}; };
@@ -76,7 +76,7 @@ public class FeedEntryFilteringService {
return true; return true;
} }
Script script = null; Script script;
try { try {
script = ENGINE.createScript(filter); script = ENGINE.createScript(filter);
} catch (JexlException e) { } catch (JexlException e) {
@@ -95,7 +95,7 @@ public class FeedEntryFilteringService {
Callable<Object> callable = script.callable(context); Callable<Object> callable = script.callable(context);
Future<Object> future = executor.submit(callable); Future<Object> future = executor.submit(callable);
Object result = null; Object result;
try { try {
result = future.get(500, TimeUnit.MILLISECONDS); result = future.get(500, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) { } catch (InterruptedException e) {

View File

@@ -33,8 +33,8 @@ public class FeedEntryTagService {
List<FeedEntryTag> addList = tagNames.stream() List<FeedEntryTag> addList = tagNames.stream()
.filter(name -> !existingTagNames.contains(name)) .filter(name -> !existingTagNames.contains(name))
.map(name -> new FeedEntryTag(user, entry, name)) .map(name -> new FeedEntryTag(user, entry, name))
.collect(Collectors.toList()); .toList();
List<FeedEntryTag> removeList = existingTags.stream().filter(tag -> !tagNames.contains(tag.getName())).collect(Collectors.toList()); List<FeedEntryTag> removeList = existingTags.stream().filter(tag -> !tagNames.contains(tag.getName())).toList();
feedEntryTagDAO.saveOrUpdate(addList); feedEntryTagDAO.saveOrUpdate(addList);
feedEntryTagDAO.delete(removeList); feedEntryTagDAO.delete(removeList);

View File

@@ -16,14 +16,11 @@ public abstract class ScheduledTask {
protected abstract TimeUnit getTimeUnit(); protected abstract TimeUnit getTimeUnit();
public void register(ScheduledExecutorService executor) { public void register(ScheduledExecutorService executor) {
Runnable runnable = new Runnable() { Runnable runnable = () -> {
@Override try {
public void run() { ScheduledTask.this.run();
try { } catch (Exception e) {
ScheduledTask.this.run(); log.error(e.getMessage(), e);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
} }
}; };
log.info("registering task {} for execution every {} {}, starting in {} {}", getClass().getSimpleName(), getPeriod(), getTimeUnit(), log.info("registering task {} for execution every {} {}, starting in {} {}", getClass().getSimpleName(), getPeriod(), getTimeUnit(),

View File

@@ -33,10 +33,10 @@ public class SecurityCheckFactory implements Function<ContainerRequest, User> {
@Override @Override
public User apply(ContainerRequest req) { public User apply(ContainerRequest req) {
Optional<User> user = apiKeyLogin(); Optional<User> user = apiKeyLogin();
if (!user.isPresent()) { if (user.isEmpty()) {
user = basicAuthenticationLogin(); user = basicAuthenticationLogin();
} }
if (!user.isPresent()) { if (user.isEmpty()) {
user = cookieSessionLogin(new SessionHelper(request)); user = cookieSessionLogin(new SessionHelper(request));
} }
@@ -60,9 +60,7 @@ public class SecurityCheckFactory implements Function<ContainerRequest, User> {
Optional<User> cookieSessionLogin(SessionHelper sessionHelper) { Optional<User> cookieSessionLogin(SessionHelper sessionHelper) {
Optional<User> loggedInUser = sessionHelper.getLoggedInUser(); Optional<User> loggedInUser = sessionHelper.getLoggedInUser();
if (loggedInUser.isPresent()) { loggedInUser.ifPresent(userService::performPostLoginActivities);
userService.performPostLoginActivities(loggedInUser.get());
}
return loggedInUser; return loggedInUser;
} }

View File

@@ -4,7 +4,6 @@ import java.io.Serializable;
import java.util.Collections; import java.util.Collections;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
@@ -14,9 +13,7 @@ import com.commafeed.backend.model.FeedEntryContent;
import com.commafeed.backend.model.FeedEntryStatus; import com.commafeed.backend.model.FeedEntryStatus;
import com.commafeed.backend.model.FeedEntryTag; import com.commafeed.backend.model.FeedEntryTag;
import com.commafeed.backend.model.FeedSubscription; import com.commafeed.backend.model.FeedSubscription;
import com.rometools.rome.feed.synd.SyndContent;
import com.rometools.rome.feed.synd.SyndContentImpl; import com.rometools.rome.feed.synd.SyndContentImpl;
import com.rometools.rome.feed.synd.SyndEnclosure;
import com.rometools.rome.feed.synd.SyndEnclosureImpl; import com.rometools.rome.feed.synd.SyndEnclosureImpl;
import com.rometools.rome.feed.synd.SyndEntry; import com.rometools.rome.feed.synd.SyndEntry;
import com.rometools.rome.feed.synd.SyndEntryImpl; import com.rometools.rome.feed.synd.SyndEntryImpl;
@@ -125,7 +122,7 @@ public class Entry implements Serializable {
entry.setFeedUrl(sub.getFeed().getUrl()); entry.setFeedUrl(sub.getFeed().getUrl());
entry.setFeedLink(sub.getFeed().getLink()); entry.setFeedLink(sub.getFeed().getLink());
entry.setIconUrl(FeedUtils.getFaviconUrl(sub)); entry.setIconUrl(FeedUtils.getFaviconUrl(sub));
entry.setTags(status.getTags().stream().map(FeedEntryTag::getName).collect(Collectors.toList())); entry.setTags(status.getTags().stream().map(FeedEntryTag::getName).toList());
if (content != null) { if (content != null) {
entry.setRtl(FeedUtils.isRTL(feedEntry)); entry.setRtl(FeedUtils.isRTL(feedEntry));
@@ -158,13 +155,13 @@ public class Entry implements Serializable {
SyndContentImpl content = new SyndContentImpl(); SyndContentImpl content = new SyndContentImpl();
content.setValue(getContent()); content.setValue(getContent());
entry.setContents(Collections.<SyndContent> singletonList(content)); entry.setContents(Collections.singletonList(content));
if (getEnclosureUrl() != null) { if (getEnclosureUrl() != null) {
SyndEnclosureImpl enclosure = new SyndEnclosureImpl(); SyndEnclosureImpl enclosure = new SyndEnclosureImpl();
enclosure.setType(getEnclosureType()); enclosure.setType(getEnclosureType());
enclosure.setUrl(getEnclosureUrl()); enclosure.setUrl(getEnclosureUrl());
entry.setEnclosures(Collections.<SyndEnclosure> singletonList(enclosure)); entry.setEnclosures(Collections.singletonList(enclosure));
} }
entry.setLink(getUrl()); entry.setLink(getUrl());

View File

@@ -2,15 +2,12 @@ package com.commafeed.frontend.resource;
import java.io.StringWriter; import java.io.StringWriter;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.Date; import java.util.Date;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.ObjectUtils;
@@ -136,7 +133,7 @@ public class CategoryREST {
List<Long> excludedIds = null; List<Long> excludedIds = null;
if (StringUtils.isNotEmpty(excludedSubscriptionIds)) { if (StringUtils.isNotEmpty(excludedSubscriptionIds)) {
excludedIds = Arrays.stream(excludedSubscriptionIds.split(",")).map(Long::valueOf).collect(Collectors.toList()); excludedIds = Arrays.stream(excludedSubscriptionIds.split(",")).map(Long::valueOf).toList();
} }
if (ALL.equals(id)) { if (ALL.equals(id)) {
@@ -220,7 +217,7 @@ public class CategoryREST {
feed.setTitle("CommaFeed - " + entries.getName()); feed.setTitle("CommaFeed - " + entries.getName());
feed.setDescription("CommaFeed - " + entries.getName()); feed.setDescription("CommaFeed - " + entries.getName());
feed.setLink(config.getApplicationSettings().getPublicUrl()); feed.setLink(config.getApplicationSettings().getPublicUrl());
feed.setEntries(entries.getEntries().stream().map(Entry::asRss).collect(Collectors.toList())); feed.setEntries(entries.getEntries().stream().map(Entry::asRss).toList());
SyndFeedOutput output = new SyndFeedOutput(); SyndFeedOutput output = new SyndFeedOutput();
StringWriter writer = new StringWriter(); StringWriter writer = new StringWriter();
@@ -265,13 +262,7 @@ public class CategoryREST {
private void removeExcludedSubscriptions(List<FeedSubscription> subs, List<Long> excludedIds) { private void removeExcludedSubscriptions(List<FeedSubscription> subs, List<Long> excludedIds) {
if (CollectionUtils.isNotEmpty(excludedIds)) { if (CollectionUtils.isNotEmpty(excludedIds)) {
Iterator<FeedSubscription> it = subs.iterator(); subs.removeIf(sub -> excludedIds.contains(sub.getId()));
while (it.hasNext()) {
FeedSubscription sub = it.next();
if (excludedIds.contains(sub.getId())) {
it.remove();
}
}
} }
} }
@@ -361,12 +352,7 @@ public class CategoryREST {
if (req.getPosition() != null) { if (req.getPosition() != null) {
List<FeedCategory> categories = feedCategoryDAO.findByParent(user, parent); List<FeedCategory> categories = feedCategoryDAO.findByParent(user, parent);
Collections.sort(categories, new Comparator<FeedCategory>() { categories.sort((o1, o2) -> ObjectUtils.compare(o1.getPosition(), o2.getPosition()));
@Override
public int compare(FeedCategory o1, FeedCategory o2) {
return ObjectUtils.compare(o1.getPosition(), o2.getPosition());
}
});
int existingIndex = -1; int existingIndex = -1;
for (int i = 0; i < categories.size(); i++) { for (int i = 0; i < categories.size(); i++) {

View File

@@ -65,7 +65,8 @@ public class EntryREST {
Preconditions.checkNotNull(req.getRequests()); Preconditions.checkNotNull(req.getRequests());
for (MarkRequest r : req.getRequests()) { for (MarkRequest r : req.getRequests()) {
markEntry(user, r); Preconditions.checkNotNull(r.getId());
feedEntryService.markEntry(user, Long.valueOf(r.getId()), r.isRead());
} }
return Response.ok().build(); return Response.ok().build();

View File

@@ -6,11 +6,9 @@ import java.net.URI;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Calendar; import java.util.Calendar;
import java.util.Collections; import java.util.Collections;
import java.util.Comparator;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.stream.Collectors;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.ObjectUtils;
@@ -225,7 +223,7 @@ public class FeedREST {
feed.setTitle("CommaFeed - " + entries.getName()); feed.setTitle("CommaFeed - " + entries.getName());
feed.setDescription("CommaFeed - " + entries.getName()); feed.setDescription("CommaFeed - " + entries.getName());
feed.setLink(config.getApplicationSettings().getPublicUrl()); feed.setLink(config.getApplicationSettings().getPublicUrl());
feed.setEntries(entries.getEntries().stream().map(Entry::asRss).collect(Collectors.toList())); feed.setEntries(entries.getEntries().stream().map(Entry::asRss).toList());
SyndFeedOutput output = new SyndFeedOutput(); SyndFeedOutput output = new SyndFeedOutput();
StringWriter writer = new StringWriter(); StringWriter writer = new StringWriter();
@@ -239,7 +237,7 @@ public class FeedREST {
} }
private FeedInfo fetchFeedInternal(String url) { private FeedInfo fetchFeedInternal(String url) {
FeedInfo info = null; FeedInfo info;
url = StringUtils.trimToEmpty(url); url = StringUtils.trimToEmpty(url);
url = prependHttp(url); url = prependHttp(url);
try { try {
@@ -268,7 +266,7 @@ public class FeedREST {
Preconditions.checkNotNull(req); Preconditions.checkNotNull(req);
Preconditions.checkNotNull(req.getUrl()); Preconditions.checkNotNull(req.getUrl());
FeedInfo info = null; FeedInfo info;
try { try {
info = fetchFeedInternal(req.getUrl()); info = fetchFeedInternal(req.getUrl());
} catch (Exception e) { } catch (Exception e) {
@@ -490,12 +488,7 @@ public class FeedREST {
if (req.getPosition() != null) { if (req.getPosition() != null) {
List<FeedSubscription> subs = feedSubscriptionDAO.findByCategory(user, parent); List<FeedSubscription> subs = feedSubscriptionDAO.findByCategory(user, parent);
Collections.sort(subs, new Comparator<FeedSubscription>() { subs.sort((o1, o2) -> ObjectUtils.compare(o1.getPosition(), o2.getPosition()));
@Override
public int compare(FeedSubscription o1, FeedSubscription o2) {
return ObjectUtils.compare(o1.getPosition(), o2.getPosition());
}
});
int existingIndex = -1; int existingIndex = -1;
for (int i = 0; i < subs.size(); i++) { for (int i = 0; i < subs.size(); i++) {
@@ -549,7 +542,7 @@ public class FeedREST {
public Response exportOpml(@Parameter(hidden = true) @SecurityCheck User user) { public Response exportOpml(@Parameter(hidden = true) @SecurityCheck User user) {
Opml opml = opmlExporter.export(user); Opml opml = opmlExporter.export(user);
WireFeedOutput output = new WireFeedOutput(); WireFeedOutput output = new WireFeedOutput();
String opmlString = null; String opmlString;
try { try {
opmlString = output.outputString(opml); opmlString = output.outputString(opml);
} catch (Exception e) { } catch (Exception e) {

View File

@@ -206,7 +206,7 @@ public class UserREST {
} }
Optional<User> login = userService.login(user.getEmail(), request.getCurrentPassword()); Optional<User> login = userService.login(user.getEmail(), request.getCurrentPassword());
if (!login.isPresent()) { if (login.isEmpty()) {
throw new BadRequestException("invalid password"); throw new BadRequestException("invalid password");
} }

View File

@@ -167,7 +167,7 @@ public class FeverREST {
if (params.containsKey("items")) { if (params.containsKey("items")) {
if (params.containsKey("with_ids")) { if (params.containsKey("with_ids")) {
String withIds = params.get("with_ids"); String withIds = params.get("with_ids");
List<String> entryIds = Stream.of(withIds.split(",")).map(String::trim).collect(Collectors.toList()); List<String> entryIds = Stream.of(withIds.split(",")).map(String::trim).toList();
resp.setItems(buildItems(user, subscriptions, entryIds)); resp.setItems(buildItems(user, subscriptions, entryIds));
} else { } else {
Long sinceId = params.containsKey("since_id") ? Long.valueOf(params.get("since_id")) : null; Long sinceId = params.containsKey("since_id") ? Long.valueOf(params.get("since_id")) : null;
@@ -216,10 +216,10 @@ public class FeverREST {
.map(e -> { .map(e -> {
FeverFeedGroup fg = new FeverFeedGroup(); FeverFeedGroup fg = new FeverFeedGroup();
fg.setGroupId(e.getKey()); fg.setGroupId(e.getKey());
fg.setFeedIds(e.getValue().stream().map(FeedSubscription::getId).collect(Collectors.toList())); fg.setFeedIds(e.getValue().stream().map(FeedSubscription::getId).toList());
return fg; return fg;
}) })
.collect(Collectors.toList()); .toList();
} }
private List<FeverGroup> buildGroups(List<FeedCategory> categories) { private List<FeverGroup> buildGroups(List<FeedCategory> categories) {
@@ -228,7 +228,7 @@ public class FeverREST {
g.setId(c.getId()); g.setId(c.getId());
g.setTitle(c.getName()); g.setTitle(c.getName());
return g; return g;
}).collect(Collectors.toList()); }).toList();
} }
private List<FeverFeed> buildFeeds(List<FeedSubscription> subscriptions) { private List<FeverFeed> buildFeeds(List<FeedSubscription> subscriptions) {
@@ -242,18 +242,18 @@ public class FeverREST {
f.setSpark(false); f.setSpark(false);
f.setLastUpdatedOnTime(s.getFeed().getLastUpdated() == null ? 0 : s.getFeed().getLastUpdated().toInstant().getEpochSecond()); f.setLastUpdatedOnTime(s.getFeed().getLastUpdated() == null ? 0 : s.getFeed().getLastUpdated().toInstant().getEpochSecond());
return f; return f;
}).collect(Collectors.toList()); }).toList();
} }
private List<Long> buildUnreadItemIds(User user, List<FeedSubscription> subscriptions) { private List<Long> buildUnreadItemIds(User user, List<FeedSubscription> subscriptions) {
List<FeedEntryStatus> statuses = feedEntryStatusDAO.findBySubscriptions(user, subscriptions, true, null, null, 0, List<FeedEntryStatus> statuses = feedEntryStatusDAO.findBySubscriptions(user, subscriptions, true, null, null, 0,
UNREAD_ITEM_IDS_BATCH_SIZE, ReadingOrder.desc, false, true, null, null, null); UNREAD_ITEM_IDS_BATCH_SIZE, ReadingOrder.desc, false, true, null, null, null);
return statuses.stream().map(s -> s.getEntry().getId()).collect(Collectors.toList()); return statuses.stream().map(s -> s.getEntry().getId()).toList();
} }
private List<Long> buildSavedItemIds(User user) { private List<Long> buildSavedItemIds(User user) {
List<FeedEntryStatus> statuses = feedEntryStatusDAO.findStarred(user, null, 0, SAVED_ITEM_IDS_BATCH_SIZE, ReadingOrder.desc, false); List<FeedEntryStatus> statuses = feedEntryStatusDAO.findStarred(user, null, 0, SAVED_ITEM_IDS_BATCH_SIZE, ReadingOrder.desc, false);
return statuses.stream().map(s -> s.getEntry().getId()).collect(Collectors.toList()); return statuses.stream().map(s -> s.getEntry().getId()).toList();
} }
private List<FeverItem> buildItems(User user, List<FeedSubscription> subscriptions, List<String> entryIds) { private List<FeverItem> buildItems(User user, List<FeedSubscription> subscriptions, List<String> entryIds) {
@@ -276,7 +276,7 @@ public class FeverREST {
private List<FeverItem> buildItems(User user, List<FeedSubscription> subscriptions, Long sinceId, Long maxId) { private List<FeverItem> buildItems(User user, List<FeedSubscription> subscriptions, Long sinceId, Long maxId) {
List<FeedEntryStatus> statuses = feedEntryStatusDAO.findBySubscriptions(user, subscriptions, false, null, null, 0, ITEMS_BATCH_SIZE, List<FeedEntryStatus> statuses = feedEntryStatusDAO.findBySubscriptions(user, subscriptions, false, null, null, 0, ITEMS_BATCH_SIZE,
ReadingOrder.desc, false, false, null, sinceId, maxId); ReadingOrder.desc, false, false, null, sinceId, maxId);
return statuses.stream().map(this::mapStatus).collect(Collectors.toList()); return statuses.stream().map(this::mapStatus).toList();
} }
private FeverItem mapStatus(FeedEntryStatus s) { private FeverItem mapStatus(FeedEntryStatus s) {
@@ -301,7 +301,7 @@ public class FeverREST {
f.setId(s.getFeed().getId()); f.setId(s.getFeed().getId());
f.setData(String.format("data:%s;base64,%s", favicon.getMediaType(), Base64.getEncoder().encodeToString(favicon.getIcon()))); f.setData(String.format("data:%s;base64,%s", favicon.getMediaType(), Base64.getEncoder().encodeToString(favicon.getIcon())));
return f; return f;
}).collect(Collectors.toList()); }).toList();
} }
private void mark(User user, String source, long id, String action, Date olderThan) { private void mark(User user, String source, long id, String action, Date olderThan) {

View File

@@ -172,7 +172,7 @@ public class FeverResponse {
@Override @Override
public List<Long> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { public List<Long> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
String value = ctxt.readValue(p, String.class); String value = ctxt.readValue(p, String.class);
return Stream.of(value.split(",")).map(Long::valueOf).collect(Collectors.toList()); return Stream.of(value.split(",")).map(Long::valueOf).toList();
} }
} }
} }

View File

@@ -27,7 +27,7 @@ abstract class AbstractCustomCodeServlet extends HttpServlet {
resp.setContentType(getMimeType()); resp.setContentType(getMimeType());
final Optional<User> user = new SessionHelper(req).getLoggedInUser(); final Optional<User> user = new SessionHelper(req).getLoggedInUser();
if (!user.isPresent()) { if (user.isEmpty()) {
return; return;
} }

View File

@@ -6,7 +6,6 @@ import com.commafeed.CommaFeedConfiguration;
import jakarta.inject.Inject; import jakarta.inject.Inject;
import jakarta.inject.Singleton; import jakarta.inject.Singleton;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
@@ -20,7 +19,7 @@ public class LogoutServlet extends HttpServlet {
private final CommaFeedConfiguration config; private final CommaFeedConfiguration config;
@Override @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
req.getSession().invalidate(); req.getSession().invalidate();
resp.sendRedirect(resp.encodeRedirectURL(config.getApplicationSettings().getPublicUrl())); resp.sendRedirect(resp.encodeRedirectURL(config.getApplicationSettings().getPublicUrl()));
} }

View File

@@ -24,7 +24,6 @@ import com.google.common.collect.Iterables;
import jakarta.inject.Inject; import jakarta.inject.Inject;
import jakarta.inject.Singleton; import jakarta.inject.Singleton;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
@@ -47,16 +46,14 @@ public class NextUnreadServlet extends HttpServlet {
private final CommaFeedConfiguration config; private final CommaFeedConfiguration config;
@Override @Override
protected void doGet(final HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { protected void doGet(final HttpServletRequest req, HttpServletResponse resp) throws IOException {
final String categoryId = req.getParameter(PARAM_CATEGORYID); final String categoryId = req.getParameter(PARAM_CATEGORYID);
String orderParam = req.getParameter(PARAM_READINGORDER); String orderParam = req.getParameter(PARAM_READINGORDER);
SessionHelper sessionHelper = new SessionHelper(req); SessionHelper sessionHelper = new SessionHelper(req);
Optional<User> user = sessionHelper.getLoggedInUser(); Optional<User> user = sessionHelper.getLoggedInUser();
if (user.isPresent()) { user.ifPresent(value -> unitOfWork.run(() -> userService.performPostLoginActivities(value)));
unitOfWork.run(() -> userService.performPostLoginActivities(user.get())); if (user.isEmpty()) {
}
if (!user.isPresent()) {
resp.sendRedirect(resp.encodeRedirectURL(config.getApplicationSettings().getPublicUrl())); resp.sendRedirect(resp.encodeRedirectURL(config.getApplicationSettings().getPublicUrl()));
return; return;
} }

View File

@@ -27,15 +27,13 @@ public class WebSocketConfigurator extends Configurator {
HttpSession httpSession = (HttpSession) request.getHttpSession(); HttpSession httpSession = (HttpSession) request.getHttpSession();
if (httpSession != null) { if (httpSession != null) {
Optional<User> user = SessionHelper.getLoggedInUser(httpSession); Optional<User> user = SessionHelper.getLoggedInUser(httpSession);
if (user.isPresent()) { user.ifPresent(value -> config.getUserProperties().put(SESSIONKEY_USERID, value.getId()));
config.getUserProperties().put(SESSIONKEY_USERID, user.get().getId());
}
} }
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException { public <T> T getEndpointInstance(Class<T> endpointClass) {
return (T) new WebSocketEndpoint(webSocketSessions); return (T) new WebSocketEndpoint(webSocketSessions);
} }
} }

View File

@@ -9,12 +9,7 @@ import org.junit.jupiter.api.Test;
class FixedSizeSortedSetTest { class FixedSizeSortedSetTest {
private static final Comparator<String> COMP = new Comparator<String>() { private static final Comparator<String> COMP = ObjectUtils::compare;
@Override
public int compare(String o1, String o2) {
return ObjectUtils.compare(o1, o2);
}
};
private FixedSizeSortedSet<String> set; private FixedSizeSortedSet<String> set;

View File

@@ -7,9 +7,10 @@ import java.util.List;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.mockito.MockitoAnnotations; import org.mockito.junit.jupiter.MockitoExtension;
import com.commafeed.backend.dao.FeedCategoryDAO; import com.commafeed.backend.dao.FeedCategoryDAO;
import com.commafeed.backend.dao.FeedSubscriptionDAO; import com.commafeed.backend.dao.FeedSubscriptionDAO;
@@ -20,6 +21,7 @@ import com.commafeed.backend.model.User;
import com.rometools.opml.feed.opml.Opml; import com.rometools.opml.feed.opml.Opml;
import com.rometools.opml.feed.opml.Outline; import com.rometools.opml.feed.opml.Outline;
@ExtendWith(MockitoExtension.class)
class OPMLExporterTest { class OPMLExporterTest {
@Mock @Mock
@@ -41,21 +43,19 @@ class OPMLExporterTest {
@BeforeEach @BeforeEach
public void init() { public void init() {
MockitoAnnotations.openMocks(this);
user.setName("John Doe"); user.setName("John Doe");
cat1.setId(1L); cat1.setId(1L);
cat1.setName("cat1"); cat1.setName("cat1");
cat1.setParent(null); cat1.setParent(null);
cat1.setChildren(new HashSet<FeedCategory>()); cat1.setChildren(new HashSet<>());
cat1.setSubscriptions(new HashSet<FeedSubscription>()); cat1.setSubscriptions(new HashSet<>());
cat2.setId(2L); cat2.setId(2L);
cat2.setName("cat2"); cat2.setName("cat2");
cat2.setParent(cat1); cat2.setParent(cat1);
cat2.setChildren(new HashSet<FeedCategory>()); cat2.setChildren(new HashSet<>());
cat2.setSubscriptions(new HashSet<FeedSubscription>()); cat2.setSubscriptions(new HashSet<>());
cat1.getChildren().add(cat2); cat1.getChildren().add(cat2);

View File

@@ -13,7 +13,6 @@ class FeedEntryFilteringServiceTest {
private FeedEntryFilteringService service; private FeedEntryFilteringService service;
private FeedEntry entry; private FeedEntry entry;
private FeedEntryContent content;
@BeforeEach @BeforeEach
public void init() { public void init() {
@@ -22,7 +21,7 @@ class FeedEntryFilteringServiceTest {
entry = new FeedEntry(); entry = new FeedEntry();
entry.setUrl("https://github.com/Athou/commafeed"); entry.setUrl("https://github.com/Athou/commafeed");
content = new FeedEntryContent(); FeedEntryContent content = new FeedEntryContent();
content.setAuthor("Athou"); content.setAuthor("Athou");
content.setTitle("Merge pull request #662 from Athou/dw8"); content.setTitle("Merge pull request #662 from Athou/dw8");
content.setContent("Merge pull request #662 from Athou/dw8"); content.setContent("Merge pull request #662 from Athou/dw8");
@@ -46,13 +45,13 @@ class FeedEntryFilteringServiceTest {
} }
@Test @Test
void newIsDisabled() throws FeedEntryFilterException { void newIsDisabled() {
Assertions.assertThrows(FeedEntryFilterException.class, Assertions.assertThrows(FeedEntryFilterException.class,
() -> service.filterMatchesEntry("null eq new ('java.lang.String', 'athou')", entry)); () -> service.filterMatchesEntry("null eq new ('java.lang.String', 'athou')", entry));
} }
@Test @Test
void getClassMethodIsDisabled() throws FeedEntryFilterException { void getClassMethodIsDisabled() {
Assertions.assertThrows(FeedEntryFilterException.class, () -> service.filterMatchesEntry("null eq ''.getClass()", entry)); Assertions.assertThrows(FeedEntryFilterException.class, () -> service.filterMatchesEntry("null eq ''.getClass()", entry));
} }
@@ -62,24 +61,24 @@ class FeedEntryFilteringServiceTest {
} }
@Test @Test
void cannotLoopForever() throws FeedEntryFilterException { void cannotLoopForever() {
Assertions.assertThrows(FeedEntryFilterException.class, () -> service.filterMatchesEntry("while(true) {}", entry)); Assertions.assertThrows(FeedEntryFilterException.class, () -> service.filterMatchesEntry("while(true) {}", entry));
} }
@Test @Test
void handlesNullCorrectly() throws FeedEntryFilterException { void handlesNullCorrectly() {
entry.setUrl(null); entry.setUrl(null);
entry.setContent(new FeedEntryContent()); entry.setContent(new FeedEntryContent());
Assertions.assertDoesNotThrow(() -> service.filterMatchesEntry("author eq 'athou'", entry)); Assertions.assertDoesNotThrow(() -> service.filterMatchesEntry("author eq 'athou'", entry));
} }
@Test @Test
void incorrectScriptThrowsException() throws FeedEntryFilterException { void incorrectScriptThrowsException() {
Assertions.assertThrows(FeedEntryFilterException.class, () -> service.filterMatchesEntry("aa eqz bb", entry)); Assertions.assertThrows(FeedEntryFilterException.class, () -> service.filterMatchesEntry("aa eqz bb", entry));
} }
@Test @Test
void incorrectReturnTypeThrowsException() throws FeedEntryFilterException { void incorrectReturnTypeThrowsException() {
Assertions.assertThrows(FeedEntryFilterException.class, () -> service.filterMatchesEntry("1", entry)); Assertions.assertThrows(FeedEntryFilterException.class, () -> service.filterMatchesEntry("1", entry));
} }

View File

@@ -5,9 +5,10 @@ import java.util.Optional;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.mockito.MockitoAnnotations; import org.mockito.junit.jupiter.MockitoExtension;
import com.commafeed.CommaFeedConfiguration; import com.commafeed.CommaFeedConfiguration;
import com.commafeed.backend.dao.FeedCategoryDAO; import com.commafeed.backend.dao.FeedCategoryDAO;
@@ -18,6 +19,7 @@ import com.commafeed.backend.dao.UserSettingsDAO;
import com.commafeed.backend.model.User; import com.commafeed.backend.model.User;
import com.commafeed.backend.service.internal.PostLoginActivities; import com.commafeed.backend.service.internal.PostLoginActivities;
@ExtendWith(MockitoExtension.class)
class UserServiceTest { class UserServiceTest {
private static final byte[] SALT = new byte[] { 1, 2, 3 }; private static final byte[] SALT = new byte[] { 1, 2, 3 };
@@ -47,8 +49,6 @@ class UserServiceTest {
@BeforeEach @BeforeEach
public void init() { public void init() {
MockitoAnnotations.openMocks(this);
userService = new UserService(feedCategoryDAO, feedSubscriptionDAO, userDAO, userRoleDAO, userSettingsDAO, userService = new UserService(feedCategoryDAO, feedSubscriptionDAO, userDAO, userRoleDAO, userSettingsDAO,
passwordEncryptionService, commaFeedConfiguration, postLoginActivities); passwordEncryptionService, commaFeedConfiguration, postLoginActivities);

View File

@@ -63,7 +63,7 @@ public class PlaywrightTestBase {
private final String directory = buildDirectory + "/playwright-artifacts"; private final String directory = buildDirectory + "/playwright-artifacts";
@Override @Override
public void beforeEach(ExtensionContext context) throws Exception { public void beforeEach(ExtensionContext context) {
PlaywrightTestBase testInstance = getTestInstance(context); PlaywrightTestBase testInstance = getTestInstance(context);
NewContextOptions newContextOptions = new Browser.NewContextOptions().setRecordVideoDir(Paths.get(directory)); NewContextOptions newContextOptions = new Browser.NewContextOptions().setRecordVideoDir(Paths.get(directory));

View File

@@ -178,11 +178,19 @@ class FeedIT extends BaseIT {
void importExportOpml() throws IOException { void importExportOpml() throws IOException {
importOpml(); importOpml();
String opml = getClient().target(getApiBaseUrl() + "feed/export").request().get(String.class); String opml = getClient().target(getApiBaseUrl() + "feed/export").request().get(String.class);
String expextedOpml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<opml version=\"1.0\">\n" + " <head>\n" String expextedOpml = """
+ " <title>admin subscriptions in CommaFeed</title>\n" + " </head>\n" + " <body>\n" <?xml version="1.0" encoding="UTF-8"?>
+ " <outline text=\"out1\" title=\"out1\">\n" <opml version="1.0">
+ " <outline text=\"feed1\" type=\"rss\" title=\"feed1\" xmlUrl=\"https://hostname.local/commafeed/feed1.xml\" />\n" <head>
+ " </outline>\n" + " </body>\n" + "</opml>\n"; <title>admin subscriptions in CommaFeed</title>
</head>
<body>
<outline text="out1" title="out1">
<outline text="feed1" type="rss" title="feed1" xmlUrl="https://hostname.local/commafeed/feed1.xml" />
</outline>
</body>
</opml>
""";
Assertions.assertEquals(StringUtils.normalizeSpace(expextedOpml), StringUtils.normalizeSpace(opml)); Assertions.assertEquals(StringUtils.normalizeSpace(expextedOpml), StringUtils.normalizeSpace(opml));
} }