forked from Archives/Athou_commafeed
fix formatting
This commit is contained in:
@@ -141,7 +141,9 @@ public class CommaFeedApplication extends Application<CommaFeedConfiguration> {
|
||||
// Scheduled tasks
|
||||
Set<ScheduledTask> tasks = injector.getInstance(Key.get(new TypeLiteral<Set<ScheduledTask>>() {
|
||||
}));
|
||||
ScheduledExecutorService executor = environment.lifecycle().scheduledExecutorService("task-scheduler", true).threads(tasks.size())
|
||||
ScheduledExecutorService executor = environment.lifecycle()
|
||||
.scheduledExecutorService("task-scheduler", true)
|
||||
.threads(tasks.size())
|
||||
.build();
|
||||
for (ScheduledTask task : tasks) {
|
||||
task.register(executor);
|
||||
|
||||
@@ -1,60 +1,60 @@
|
||||
package com.commafeed.backend;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
|
||||
import org.apache.http.Header;
|
||||
import org.apache.http.HeaderElement;
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.HttpException;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.HttpResponseInterceptor;
|
||||
import org.apache.http.entity.HttpEntityWrapper;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
|
||||
class ContentEncodingInterceptor implements HttpResponseInterceptor {
|
||||
|
||||
private static final Set<String> ALLOWED_CONTENT_ENCODINGS = new HashSet<>(Arrays.asList("gzip", "x-gzip", "deflate", "identity"));
|
||||
|
||||
@Override
|
||||
public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
|
||||
if (hasContent(response)) {
|
||||
Header contentEncodingHeader = response.getEntity().getContentEncoding();
|
||||
if (contentEncodingHeader != null && containsUnsupportedEncodings(contentEncodingHeader)) {
|
||||
overrideContentEncoding(response);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean containsUnsupportedEncodings(Header contentEncodingHeader) {
|
||||
HeaderElement[] codecs = contentEncodingHeader.getElements();
|
||||
|
||||
for (final HeaderElement codec : codecs) {
|
||||
String codecName = codec.getName().toLowerCase(Locale.US);
|
||||
if (!ALLOWED_CONTENT_ENCODINGS.contains(codecName)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private void overrideContentEncoding(HttpResponse response) {
|
||||
HttpEntity wrapped = new HttpEntityWrapper(response.getEntity()) {
|
||||
@Override
|
||||
public Header getContentEncoding() {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
response.setEntity(wrapped);
|
||||
}
|
||||
|
||||
private boolean hasContent(HttpResponse response) {
|
||||
return response.getEntity() != null && response.getEntity().getContentLength() != 0;
|
||||
}
|
||||
|
||||
}
|
||||
package com.commafeed.backend;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
|
||||
import org.apache.http.Header;
|
||||
import org.apache.http.HeaderElement;
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.HttpException;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.HttpResponseInterceptor;
|
||||
import org.apache.http.entity.HttpEntityWrapper;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
|
||||
class ContentEncodingInterceptor implements HttpResponseInterceptor {
|
||||
|
||||
private static final Set<String> ALLOWED_CONTENT_ENCODINGS = new HashSet<>(Arrays.asList("gzip", "x-gzip", "deflate", "identity"));
|
||||
|
||||
@Override
|
||||
public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
|
||||
if (hasContent(response)) {
|
||||
Header contentEncodingHeader = response.getEntity().getContentEncoding();
|
||||
if (contentEncodingHeader != null && containsUnsupportedEncodings(contentEncodingHeader)) {
|
||||
overrideContentEncoding(response);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean containsUnsupportedEncodings(Header contentEncodingHeader) {
|
||||
HeaderElement[] codecs = contentEncodingHeader.getElements();
|
||||
|
||||
for (final HeaderElement codec : codecs) {
|
||||
String codecName = codec.getName().toLowerCase(Locale.US);
|
||||
if (!ALLOWED_CONTENT_ENCODINGS.contains(codecName)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private void overrideContentEncoding(HttpResponse response) {
|
||||
HttpEntity wrapped = new HttpEntityWrapper(response.getEntity()) {
|
||||
@Override
|
||||
public Header getContentEncoding() {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
response.setEntity(wrapped);
|
||||
}
|
||||
|
||||
private boolean hasContent(HttpResponse response) {
|
||||
return response.getEntity() != null && response.getEntity().getContentLength() != 0;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -16,8 +16,8 @@ import com.querydsl.jpa.JPQLQuery;
|
||||
@Singleton
|
||||
public class FeedEntryContentDAO extends GenericDAO<FeedEntryContent> {
|
||||
|
||||
private QFeedEntryContent content = QFeedEntryContent.feedEntryContent;
|
||||
private QFeedEntry entry = QFeedEntry.feedEntry;
|
||||
private final QFeedEntryContent content = QFeedEntryContent.feedEntryContent;
|
||||
private final QFeedEntry entry = QFeedEntry.feedEntry;
|
||||
|
||||
@Inject
|
||||
public FeedEntryContentDAO(SessionFactory sessionFactory) {
|
||||
@@ -25,7 +25,9 @@ public class FeedEntryContentDAO extends GenericDAO<FeedEntryContent> {
|
||||
}
|
||||
|
||||
public Long findExisting(String contentHash, String titleHash) {
|
||||
return query().select(content.id).from(content).where(content.contentHash.eq(contentHash), content.titleHash.eq(titleHash))
|
||||
return query().select(content.id)
|
||||
.from(content)
|
||||
.where(content.contentHash.eq(contentHash), content.titleHash.eq(titleHash))
|
||||
.fetchFirst();
|
||||
}
|
||||
|
||||
|
||||
@@ -29,13 +29,20 @@ public class FeedEntryDAO extends GenericDAO<FeedEntry> {
|
||||
}
|
||||
|
||||
public Long findExisting(String guid, Feed feed) {
|
||||
return query().select(entry.id).from(entry).where(entry.guidHash.eq(DigestUtils.sha1Hex(guid)), entry.feed.eq(feed)).limit(1)
|
||||
return query().select(entry.id)
|
||||
.from(entry)
|
||||
.where(entry.guidHash.eq(DigestUtils.sha1Hex(guid)), entry.feed.eq(feed))
|
||||
.limit(1)
|
||||
.fetchOne();
|
||||
}
|
||||
|
||||
public List<FeedCapacity> findFeedsExceedingCapacity(long maxCapacity, long max) {
|
||||
NumberExpression<Long> count = entry.id.count();
|
||||
List<Tuple> tuples = query().select(entry.feed.id, count).from(entry).groupBy(entry.feed).having(count.gt(maxCapacity)).limit(max)
|
||||
List<Tuple> tuples = query().select(entry.feed.id, count)
|
||||
.from(entry)
|
||||
.groupBy(entry.feed)
|
||||
.having(count.gt(maxCapacity))
|
||||
.limit(max)
|
||||
.fetch();
|
||||
return tuples.stream().map(t -> new FeedCapacity(t.get(entry.feed.id), t.get(count))).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@@ -29,8 +29,13 @@ public class FeedSubscriptionDAO extends GenericDAO<FeedSubscription> {
|
||||
}
|
||||
|
||||
public FeedSubscription findById(User user, Long id) {
|
||||
List<FeedSubscription> subs = query().selectFrom(sub).where(sub.user.eq(user), sub.id.eq(id)).leftJoin(sub.feed).fetchJoin()
|
||||
.leftJoin(sub.category).fetchJoin().fetch();
|
||||
List<FeedSubscription> subs = query().selectFrom(sub)
|
||||
.where(sub.user.eq(user), sub.id.eq(id))
|
||||
.leftJoin(sub.feed)
|
||||
.fetchJoin()
|
||||
.leftJoin(sub.category)
|
||||
.fetchJoin()
|
||||
.fetch();
|
||||
return initRelations(Iterables.getFirst(subs, null));
|
||||
}
|
||||
|
||||
@@ -44,8 +49,13 @@ public class FeedSubscriptionDAO extends GenericDAO<FeedSubscription> {
|
||||
}
|
||||
|
||||
public List<FeedSubscription> findAll(User user) {
|
||||
List<FeedSubscription> subs = query().selectFrom(sub).where(sub.user.eq(user)).leftJoin(sub.feed).fetchJoin().leftJoin(sub.category)
|
||||
.fetchJoin().fetch();
|
||||
List<FeedSubscription> subs = query().selectFrom(sub)
|
||||
.where(sub.user.eq(user))
|
||||
.leftJoin(sub.feed)
|
||||
.fetchJoin()
|
||||
.leftJoin(sub.category)
|
||||
.fetchJoin()
|
||||
.fetch();
|
||||
return initRelations(subs);
|
||||
}
|
||||
|
||||
@@ -61,7 +71,8 @@ public class FeedSubscriptionDAO extends GenericDAO<FeedSubscription> {
|
||||
|
||||
public List<FeedSubscription> findByCategories(User user, List<FeedCategory> categories) {
|
||||
Set<Long> categoryIds = categories.stream().map(c -> c.getId()).collect(Collectors.toSet());
|
||||
return findAll(user).stream().filter(s -> s.getCategory() != null && categoryIds.contains(s.getCategory().getId()))
|
||||
return findAll(user).stream()
|
||||
.filter(s -> s.getCategory() != null && categoryIds.contains(s.getCategory().getId()))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
|
||||
@@ -61,13 +61,15 @@ public class OPMLExporter {
|
||||
outline.setText(cat.getName());
|
||||
outline.setTitle(cat.getName());
|
||||
|
||||
for (FeedCategory child : categories.stream().filter(c -> c.getParent() != null && c.getParent().getId().equals(cat.getId()))
|
||||
for (FeedCategory child : categories.stream()
|
||||
.filter(c -> c.getParent() != null && c.getParent().getId().equals(cat.getId()))
|
||||
.collect(Collectors.toList())) {
|
||||
outline.getChildren().add(buildCategoryOutline(child, categories, subscriptions));
|
||||
}
|
||||
|
||||
for (FeedSubscription sub : subscriptions.stream()
|
||||
.filter(s -> s.getCategory() != null && s.getCategory().getId().equals(cat.getId())).collect(Collectors.toList())) {
|
||||
.filter(s -> s.getCategory() != null && s.getCategory().getId().equals(cat.getId()))
|
||||
.collect(Collectors.toList())) {
|
||||
outline.getChildren().add(buildSubscriptionOutline(sub));
|
||||
}
|
||||
return outline;
|
||||
|
||||
@@ -1,46 +1,46 @@
|
||||
package com.commafeed.backend.service.internal;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import javax.inject.Inject;
|
||||
import javax.inject.Singleton;
|
||||
|
||||
import org.apache.commons.lang3.time.DateUtils;
|
||||
|
||||
import com.commafeed.CommaFeedConfiguration;
|
||||
import com.commafeed.backend.dao.UserDAO;
|
||||
import com.commafeed.backend.model.User;
|
||||
import com.commafeed.backend.service.FeedSubscriptionService;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
@RequiredArgsConstructor(onConstructor = @__({ @Inject }))
|
||||
@Singleton
|
||||
public class PostLoginActivities {
|
||||
|
||||
private final UserDAO userDAO;
|
||||
private final FeedSubscriptionService feedSubscriptionService;
|
||||
private final CommaFeedConfiguration config;
|
||||
|
||||
public void executeFor(User user) {
|
||||
Date lastLogin = user.getLastLogin();
|
||||
Date now = new Date();
|
||||
|
||||
boolean saveUser = false;
|
||||
// only update lastLogin field every hour in order to not
|
||||
// invalidate the cache every time someone logs in
|
||||
if (lastLogin == null || lastLogin.before(DateUtils.addHours(now, -1))) {
|
||||
user.setLastLogin(now);
|
||||
saveUser = true;
|
||||
}
|
||||
if (config.getApplicationSettings().getHeavyLoad() && user.shouldRefreshFeedsAt(now)) {
|
||||
feedSubscriptionService.refreshAll(user);
|
||||
user.setLastFullRefresh(now);
|
||||
saveUser = true;
|
||||
}
|
||||
if (saveUser) {
|
||||
userDAO.saveOrUpdate(user);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
package com.commafeed.backend.service.internal;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import javax.inject.Inject;
|
||||
import javax.inject.Singleton;
|
||||
|
||||
import org.apache.commons.lang3.time.DateUtils;
|
||||
|
||||
import com.commafeed.CommaFeedConfiguration;
|
||||
import com.commafeed.backend.dao.UserDAO;
|
||||
import com.commafeed.backend.model.User;
|
||||
import com.commafeed.backend.service.FeedSubscriptionService;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
@RequiredArgsConstructor(onConstructor = @__({ @Inject }))
|
||||
@Singleton
|
||||
public class PostLoginActivities {
|
||||
|
||||
private final UserDAO userDAO;
|
||||
private final FeedSubscriptionService feedSubscriptionService;
|
||||
private final CommaFeedConfiguration config;
|
||||
|
||||
public void executeFor(User user) {
|
||||
Date lastLogin = user.getLastLogin();
|
||||
Date now = new Date();
|
||||
|
||||
boolean saveUser = false;
|
||||
// only update lastLogin field every hour in order to not
|
||||
// invalidate the cache every time someone logs in
|
||||
if (lastLogin == null || lastLogin.before(DateUtils.addHours(now, -1))) {
|
||||
user.setLastLogin(now);
|
||||
saveUser = true;
|
||||
}
|
||||
if (config.getApplicationSettings().getHeavyLoad() && user.shouldRefreshFeedsAt(now)) {
|
||||
feedSubscriptionService.refreshAll(user);
|
||||
user.setLastFullRefresh(now);
|
||||
saveUser = true;
|
||||
}
|
||||
if (saveUser) {
|
||||
userDAO.saveOrUpdate(user);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -26,8 +26,8 @@ public abstract class ScheduledTask {
|
||||
}
|
||||
}
|
||||
};
|
||||
log.info("registering task {} for execution every {} {}, starting in {} {}", getClass().getSimpleName(), getPeriod(),
|
||||
getTimeUnit(), getInitialDelay(), getTimeUnit());
|
||||
log.info("registering task {} for execution every {} {}, starting in {} {}", getClass().getSimpleName(), getPeriod(), getTimeUnit(),
|
||||
getInitialDelay(), getTimeUnit());
|
||||
executor.scheduleWithFixedDelay(runnable, getInitialDelay(), getPeriod(), getTimeUnit());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,16 +145,18 @@ public class CategoryREST {
|
||||
offset, limit + 1, order, true, onlyIds, tag);
|
||||
|
||||
for (FeedEntryStatus status : list) {
|
||||
entries.getEntries().add(Entry.build(status, config.getApplicationSettings().getPublicUrl(),
|
||||
config.getApplicationSettings().getImageProxyEnabled()));
|
||||
entries.getEntries()
|
||||
.add(Entry.build(status, config.getApplicationSettings().getPublicUrl(),
|
||||
config.getApplicationSettings().getImageProxyEnabled()));
|
||||
}
|
||||
|
||||
} else if (STARRED.equals(id)) {
|
||||
entries.setName("Starred");
|
||||
List<FeedEntryStatus> starred = feedEntryStatusDAO.findStarred(user, newerThanDate, offset, limit + 1, order, !onlyIds);
|
||||
for (FeedEntryStatus status : starred) {
|
||||
entries.getEntries().add(Entry.build(status, config.getApplicationSettings().getPublicUrl(),
|
||||
config.getApplicationSettings().getImageProxyEnabled()));
|
||||
entries.getEntries()
|
||||
.add(Entry.build(status, config.getApplicationSettings().getPublicUrl(),
|
||||
config.getApplicationSettings().getImageProxyEnabled()));
|
||||
}
|
||||
} else {
|
||||
FeedCategory parent = feedCategoryDAO.findById(user, Long.valueOf(id));
|
||||
@@ -166,8 +168,9 @@ public class CategoryREST {
|
||||
offset, limit + 1, order, true, onlyIds, tag);
|
||||
|
||||
for (FeedEntryStatus status : list) {
|
||||
entries.getEntries().add(Entry.build(status, config.getApplicationSettings().getPublicUrl(),
|
||||
config.getApplicationSettings().getImageProxyEnabled()));
|
||||
entries.getEntries()
|
||||
.add(Entry.build(status, config.getApplicationSettings().getPublicUrl(),
|
||||
config.getApplicationSettings().getImageProxyEnabled()));
|
||||
}
|
||||
entries.setName(parent.getName());
|
||||
} else {
|
||||
|
||||
@@ -1,40 +1,40 @@
|
||||
package com.commafeed.frontend.session;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import com.commafeed.backend.model.User;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
@RequiredArgsConstructor()
|
||||
public class SessionHelper {
|
||||
|
||||
private static final String SESSION_KEY_USER = "user";
|
||||
|
||||
private final HttpServletRequest request;
|
||||
|
||||
public Optional<User> getLoggedInUser() {
|
||||
Optional<HttpSession> session = getSession(false);
|
||||
|
||||
if (session.isPresent()) {
|
||||
User user = (User) session.get().getAttribute(SESSION_KEY_USER);
|
||||
return Optional.ofNullable(user);
|
||||
}
|
||||
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
public void setLoggedInUser(User user) {
|
||||
Optional<HttpSession> session = getSession(true);
|
||||
session.get().setAttribute(SESSION_KEY_USER, user);
|
||||
}
|
||||
|
||||
private Optional<HttpSession> getSession(boolean force) {
|
||||
HttpSession session = request.getSession(force);
|
||||
return Optional.ofNullable(session);
|
||||
}
|
||||
|
||||
}
|
||||
package com.commafeed.frontend.session;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import com.commafeed.backend.model.User;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
@RequiredArgsConstructor()
|
||||
public class SessionHelper {
|
||||
|
||||
private static final String SESSION_KEY_USER = "user";
|
||||
|
||||
private final HttpServletRequest request;
|
||||
|
||||
public Optional<User> getLoggedInUser() {
|
||||
Optional<HttpSession> session = getSession(false);
|
||||
|
||||
if (session.isPresent()) {
|
||||
User user = (User) session.get().getAttribute(SESSION_KEY_USER);
|
||||
return Optional.ofNullable(user);
|
||||
}
|
||||
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
public void setLoggedInUser(User user) {
|
||||
Optional<HttpSession> session = getSession(true);
|
||||
session.get().setAttribute(SESSION_KEY_USER, user);
|
||||
}
|
||||
|
||||
private Optional<HttpSession> getSession(boolean force) {
|
||||
HttpSession session = request.getSession(force);
|
||||
return Optional.ofNullable(session);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
package com.commafeed.frontend.session;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.ws.rs.core.Context;
|
||||
|
||||
import org.glassfish.jersey.server.internal.inject.AbstractContainerRequestValueFactory;
|
||||
|
||||
public class SessionHelperFactory extends AbstractContainerRequestValueFactory<SessionHelper> {
|
||||
|
||||
@Context
|
||||
HttpServletRequest request;
|
||||
|
||||
@Override
|
||||
public SessionHelper provide() {
|
||||
return new SessionHelper(request);
|
||||
}
|
||||
package com.commafeed.frontend.session;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.ws.rs.core.Context;
|
||||
|
||||
import org.glassfish.jersey.server.internal.inject.AbstractContainerRequestValueFactory;
|
||||
|
||||
public class SessionHelperFactory extends AbstractContainerRequestValueFactory<SessionHelper> {
|
||||
|
||||
@Context
|
||||
HttpServletRequest request;
|
||||
|
||||
@Override
|
||||
public SessionHelper provide() {
|
||||
return new SessionHelper(request);
|
||||
}
|
||||
}
|
||||
@@ -1,99 +1,99 @@
|
||||
package com.commafeed.backend.service;
|
||||
|
||||
import org.apache.http.HttpHeaders;
|
||||
import org.junit.Before;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Answers;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockserver.client.MockServerClient;
|
||||
import org.mockserver.junit.MockServerRule;
|
||||
import org.mockserver.model.HttpRequest;
|
||||
import org.mockserver.model.HttpResponse;
|
||||
import org.mockserver.model.MediaType;
|
||||
|
||||
import com.commafeed.CommaFeedConfiguration;
|
||||
import com.commafeed.backend.feed.FeedQueues;
|
||||
import com.commafeed.backend.model.Feed;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class PubSubServiceTest {
|
||||
|
||||
private PubSubService underTest;
|
||||
|
||||
@Rule
|
||||
private final MockServerRule mockServerRule = new MockServerRule(this, 22441);
|
||||
|
||||
private MockServerClient mockServerClient;
|
||||
|
||||
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
|
||||
private CommaFeedConfiguration config;
|
||||
|
||||
@Mock
|
||||
private FeedQueues queues;
|
||||
|
||||
@Mock
|
||||
private Feed feed;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
underTest = new PubSubService(config, queues);
|
||||
|
||||
// setup feed
|
||||
feed = Mockito.mock(Feed.class);
|
||||
Mockito.when(feed.getPushHub()).thenReturn("http://localhost:22441/hub");
|
||||
Mockito.when(feed.getPushTopic()).thenReturn("foo");
|
||||
|
||||
// setup config
|
||||
Mockito.when(config.getApplicationSettings().getPublicUrl()).thenReturn("http://localhost:22441/hub");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void subscribe200() {
|
||||
// Arrange
|
||||
mockServerClient.when(HttpRequest.request().withMethod("POST")).respond(HttpResponse.response().withStatusCode(200));
|
||||
|
||||
// Act
|
||||
underTest.subscribe(feed);
|
||||
|
||||
// Assert
|
||||
mockServerClient.verify(HttpRequest.request()
|
||||
.withContentType(MediaType.APPLICATION_FORM_URLENCODED)
|
||||
.withHeader(HttpHeaders.USER_AGENT, "CommaFeed")
|
||||
.withMethod("POST")
|
||||
.withPath("/hub"));
|
||||
Mockito.verify(feed, Mockito.never()).setPushTopic(Mockito.anyString());
|
||||
Mockito.verifyZeroInteractions(queues);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void subscribe400WithPushpressError() {
|
||||
// Arrange
|
||||
mockServerClient.when(HttpRequest.request().withMethod("POST"))
|
||||
.respond(HttpResponse.response().withStatusCode(400).withBody(" is value is not allowed. You may only subscribe to"));
|
||||
|
||||
// Act
|
||||
underTest.subscribe(feed);
|
||||
|
||||
// Assert
|
||||
Mockito.verify(feed).setPushTopic(Mockito.anyString());
|
||||
Mockito.verify(queues).giveBack(feed);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void subscribe400WithoutPushpressError() {
|
||||
// Arrange
|
||||
mockServerClient.when(HttpRequest.request().withMethod("POST")).respond(HttpResponse.response().withStatusCode(400));
|
||||
|
||||
// Act
|
||||
underTest.subscribe(feed);
|
||||
|
||||
// Assert
|
||||
Mockito.verify(feed, Mockito.never()).setPushTopic(Mockito.anyString());
|
||||
Mockito.verifyZeroInteractions(queues);
|
||||
}
|
||||
|
||||
package com.commafeed.backend.service;
|
||||
|
||||
import org.apache.http.HttpHeaders;
|
||||
import org.junit.Before;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Answers;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockserver.client.MockServerClient;
|
||||
import org.mockserver.junit.MockServerRule;
|
||||
import org.mockserver.model.HttpRequest;
|
||||
import org.mockserver.model.HttpResponse;
|
||||
import org.mockserver.model.MediaType;
|
||||
|
||||
import com.commafeed.CommaFeedConfiguration;
|
||||
import com.commafeed.backend.feed.FeedQueues;
|
||||
import com.commafeed.backend.model.Feed;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class PubSubServiceTest {
|
||||
|
||||
private PubSubService underTest;
|
||||
|
||||
@Rule
|
||||
private final MockServerRule mockServerRule = new MockServerRule(this, 22441);
|
||||
|
||||
private MockServerClient mockServerClient;
|
||||
|
||||
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
|
||||
private CommaFeedConfiguration config;
|
||||
|
||||
@Mock
|
||||
private FeedQueues queues;
|
||||
|
||||
@Mock
|
||||
private Feed feed;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
underTest = new PubSubService(config, queues);
|
||||
|
||||
// setup feed
|
||||
feed = Mockito.mock(Feed.class);
|
||||
Mockito.when(feed.getPushHub()).thenReturn("http://localhost:22441/hub");
|
||||
Mockito.when(feed.getPushTopic()).thenReturn("foo");
|
||||
|
||||
// setup config
|
||||
Mockito.when(config.getApplicationSettings().getPublicUrl()).thenReturn("http://localhost:22441/hub");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void subscribe200() {
|
||||
// Arrange
|
||||
mockServerClient.when(HttpRequest.request().withMethod("POST")).respond(HttpResponse.response().withStatusCode(200));
|
||||
|
||||
// Act
|
||||
underTest.subscribe(feed);
|
||||
|
||||
// Assert
|
||||
mockServerClient.verify(HttpRequest.request()
|
||||
.withContentType(MediaType.APPLICATION_FORM_URLENCODED)
|
||||
.withHeader(HttpHeaders.USER_AGENT, "CommaFeed")
|
||||
.withMethod("POST")
|
||||
.withPath("/hub"));
|
||||
Mockito.verify(feed, Mockito.never()).setPushTopic(Mockito.anyString());
|
||||
Mockito.verifyZeroInteractions(queues);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void subscribe400WithPushpressError() {
|
||||
// Arrange
|
||||
mockServerClient.when(HttpRequest.request().withMethod("POST"))
|
||||
.respond(HttpResponse.response().withStatusCode(400).withBody(" is value is not allowed. You may only subscribe to"));
|
||||
|
||||
// Act
|
||||
underTest.subscribe(feed);
|
||||
|
||||
// Assert
|
||||
Mockito.verify(feed).setPushTopic(Mockito.anyString());
|
||||
Mockito.verify(queues).giveBack(feed);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void subscribe400WithoutPushpressError() {
|
||||
// Arrange
|
||||
mockServerClient.when(HttpRequest.request().withMethod("POST")).respond(HttpResponse.response().withStatusCode(400));
|
||||
|
||||
// Act
|
||||
underTest.subscribe(feed);
|
||||
|
||||
// Assert
|
||||
Mockito.verify(feed, Mockito.never()).setPushTopic(Mockito.anyString());
|
||||
Mockito.verifyZeroInteractions(queues);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,194 +1,194 @@
|
||||
package com.commafeed.backend.service;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
|
||||
import com.commafeed.CommaFeedConfiguration;
|
||||
import com.commafeed.backend.dao.FeedCategoryDAO;
|
||||
import com.commafeed.backend.dao.FeedSubscriptionDAO;
|
||||
import com.commafeed.backend.dao.UserDAO;
|
||||
import com.commafeed.backend.dao.UserRoleDAO;
|
||||
import com.commafeed.backend.dao.UserSettingsDAO;
|
||||
import com.commafeed.backend.model.User;
|
||||
import com.commafeed.backend.service.internal.PostLoginActivities;
|
||||
|
||||
public class UserServiceTest {
|
||||
|
||||
private static final byte[] SALT = new byte[] { 1, 2, 3 };
|
||||
private static final byte[] ENCRYPTED_PASSWORD = new byte[] { 5, 6, 7 };
|
||||
|
||||
@Mock
|
||||
private CommaFeedConfiguration commaFeedConfiguration;
|
||||
@Mock
|
||||
private FeedCategoryDAO feedCategoryDAO;
|
||||
@Mock
|
||||
private FeedSubscriptionDAO feedSubscriptionDAO;
|
||||
@Mock
|
||||
private UserDAO userDAO;
|
||||
@Mock
|
||||
private UserSettingsDAO userSettingsDAO;
|
||||
@Mock
|
||||
private UserRoleDAO userRoleDAO;
|
||||
@Mock
|
||||
private PasswordEncryptionService passwordEncryptionService;
|
||||
@Mock
|
||||
private PostLoginActivities postLoginActivities;
|
||||
|
||||
private User disabledUser;
|
||||
private User normalUser;
|
||||
|
||||
private UserService userService;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
MockitoAnnotations.initMocks(this);
|
||||
|
||||
userService = new UserService(feedCategoryDAO, feedSubscriptionDAO, userDAO, userRoleDAO, userSettingsDAO,
|
||||
passwordEncryptionService, commaFeedConfiguration, postLoginActivities);
|
||||
|
||||
disabledUser = new User();
|
||||
disabledUser.setDisabled(true);
|
||||
|
||||
normalUser = new User();
|
||||
normalUser.setDisabled(false);
|
||||
normalUser.setSalt(SALT);
|
||||
normalUser.setPassword(ENCRYPTED_PASSWORD);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void callingLoginShouldNotReturnUserObjectWhenGivenNullNameOrEmail() {
|
||||
Optional<User> user = userService.login(null, "password");
|
||||
Assert.assertFalse(user.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void callingLoginShouldNotReturnUserObjectWhenGivenNullPassword() {
|
||||
Optional<User> user = userService.login("testusername", null);
|
||||
Assert.assertFalse(user.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void callingLoginShouldLookupUserByName() {
|
||||
userService.login("test", "password");
|
||||
Mockito.verify(userDAO).findByName("test");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void callingLoginShouldLookupUserByEmailIfLookupByNameFailed() {
|
||||
Mockito.when(userDAO.findByName("test@test.com")).thenReturn(null);
|
||||
userService.login("test@test.com", "password");
|
||||
Mockito.verify(userDAO).findByEmail("test@test.com");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void callingLoginShouldNotReturnUserObjectIfCouldNotFindUserByNameOrEmail() {
|
||||
Mockito.when(userDAO.findByName("test@test.com")).thenReturn(null);
|
||||
Mockito.when(userDAO.findByEmail("test@test.com")).thenReturn(null);
|
||||
|
||||
Optional<User> user = userService.login("test@test.com", "password");
|
||||
|
||||
Assert.assertFalse(user.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void callingLoginShouldNotReturnUserObjectIfUserIsDisabled() {
|
||||
Mockito.when(userDAO.findByName("test")).thenReturn(disabledUser);
|
||||
Optional<User> user = userService.login("test", "password");
|
||||
Assert.assertFalse(user.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void callingLoginShouldTryToAuthenticateUserWhoIsNotDisabled() {
|
||||
Mockito.when(userDAO.findByName("test")).thenReturn(normalUser);
|
||||
Mockito.when(passwordEncryptionService.authenticate(Mockito.anyString(), Mockito.any(byte[].class), Mockito.any(byte[].class)))
|
||||
.thenReturn(false);
|
||||
|
||||
userService.login("test", "password");
|
||||
|
||||
Mockito.verify(passwordEncryptionService).authenticate("password", ENCRYPTED_PASSWORD, SALT);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void callingLoginShouldNotReturnUserObjectOnUnsuccessfulAuthentication() {
|
||||
Mockito.when(userDAO.findByName("test")).thenReturn(normalUser);
|
||||
Mockito.when(passwordEncryptionService.authenticate(Mockito.anyString(), Mockito.any(byte[].class), Mockito.any(byte[].class)))
|
||||
.thenReturn(false);
|
||||
|
||||
Optional<User> authenticatedUser = userService.login("test", "password");
|
||||
|
||||
Assert.assertFalse(authenticatedUser.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void callingLoginShouldExecutePostLoginActivitiesForUserOnSuccessfulAuthentication() {
|
||||
Mockito.when(userDAO.findByName("test")).thenReturn(normalUser);
|
||||
Mockito.when(passwordEncryptionService.authenticate(Mockito.anyString(), Mockito.any(byte[].class), Mockito.any(byte[].class)))
|
||||
.thenReturn(true);
|
||||
Mockito.doNothing().when(postLoginActivities).executeFor(Mockito.any(User.class));
|
||||
|
||||
userService.login("test", "password");
|
||||
|
||||
Mockito.verify(postLoginActivities).executeFor(normalUser);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void callingLoginShouldReturnUserObjectOnSuccessfulAuthentication() {
|
||||
Mockito.when(userDAO.findByName("test")).thenReturn(normalUser);
|
||||
Mockito.when(passwordEncryptionService.authenticate(Mockito.anyString(), Mockito.any(byte[].class), Mockito.any(byte[].class)))
|
||||
.thenReturn(true);
|
||||
Mockito.doNothing().when(postLoginActivities).executeFor(Mockito.any(User.class));
|
||||
|
||||
Optional<User> authenticatedUser = userService.login("test", "password");
|
||||
|
||||
Assert.assertTrue(authenticatedUser.isPresent());
|
||||
Assert.assertEquals(normalUser, authenticatedUser.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void apiLoginShouldNotReturnUserIfApikeyNull() {
|
||||
Optional<User> user = userService.login(null);
|
||||
Assert.assertFalse(user.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void apiLoginShouldLookupUserByApikey() {
|
||||
Mockito.when(userDAO.findByApiKey("apikey")).thenReturn(null);
|
||||
userService.login("apikey");
|
||||
Mockito.verify(userDAO).findByApiKey("apikey");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void apiLoginShouldNotReturnUserIfUserNotFoundFromLookupByApikey() {
|
||||
Mockito.when(userDAO.findByApiKey("apikey")).thenReturn(null);
|
||||
Optional<User> user = userService.login("apikey");
|
||||
Assert.assertFalse(user.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void apiLoginShouldNotReturnUserIfUserFoundFromApikeyLookupIsDisabled() {
|
||||
Mockito.when(userDAO.findByApiKey("apikey")).thenReturn(disabledUser);
|
||||
Optional<User> user = userService.login("apikey");
|
||||
Assert.assertFalse(user.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void apiLoginShouldPerformPostLoginActivitiesIfUserFoundFromApikeyLookupNotDisabled() {
|
||||
Mockito.when(userDAO.findByApiKey("apikey")).thenReturn(normalUser);
|
||||
userService.login("apikey");
|
||||
Mockito.verify(postLoginActivities).executeFor(normalUser);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void apiLoginShouldReturnUserIfUserFoundFromApikeyLookupNotDisabled() {
|
||||
Mockito.when(userDAO.findByApiKey("apikey")).thenReturn(normalUser);
|
||||
Optional<User> returnedUser = userService.login("apikey");
|
||||
Assert.assertEquals(normalUser, returnedUser.get());
|
||||
}
|
||||
|
||||
}
|
||||
package com.commafeed.backend.service;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
|
||||
import com.commafeed.CommaFeedConfiguration;
|
||||
import com.commafeed.backend.dao.FeedCategoryDAO;
|
||||
import com.commafeed.backend.dao.FeedSubscriptionDAO;
|
||||
import com.commafeed.backend.dao.UserDAO;
|
||||
import com.commafeed.backend.dao.UserRoleDAO;
|
||||
import com.commafeed.backend.dao.UserSettingsDAO;
|
||||
import com.commafeed.backend.model.User;
|
||||
import com.commafeed.backend.service.internal.PostLoginActivities;
|
||||
|
||||
public class UserServiceTest {
|
||||
|
||||
private static final byte[] SALT = new byte[] { 1, 2, 3 };
|
||||
private static final byte[] ENCRYPTED_PASSWORD = new byte[] { 5, 6, 7 };
|
||||
|
||||
@Mock
|
||||
private CommaFeedConfiguration commaFeedConfiguration;
|
||||
@Mock
|
||||
private FeedCategoryDAO feedCategoryDAO;
|
||||
@Mock
|
||||
private FeedSubscriptionDAO feedSubscriptionDAO;
|
||||
@Mock
|
||||
private UserDAO userDAO;
|
||||
@Mock
|
||||
private UserSettingsDAO userSettingsDAO;
|
||||
@Mock
|
||||
private UserRoleDAO userRoleDAO;
|
||||
@Mock
|
||||
private PasswordEncryptionService passwordEncryptionService;
|
||||
@Mock
|
||||
private PostLoginActivities postLoginActivities;
|
||||
|
||||
private User disabledUser;
|
||||
private User normalUser;
|
||||
|
||||
private UserService userService;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
MockitoAnnotations.initMocks(this);
|
||||
|
||||
userService = new UserService(feedCategoryDAO, feedSubscriptionDAO, userDAO, userRoleDAO, userSettingsDAO,
|
||||
passwordEncryptionService, commaFeedConfiguration, postLoginActivities);
|
||||
|
||||
disabledUser = new User();
|
||||
disabledUser.setDisabled(true);
|
||||
|
||||
normalUser = new User();
|
||||
normalUser.setDisabled(false);
|
||||
normalUser.setSalt(SALT);
|
||||
normalUser.setPassword(ENCRYPTED_PASSWORD);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void callingLoginShouldNotReturnUserObjectWhenGivenNullNameOrEmail() {
|
||||
Optional<User> user = userService.login(null, "password");
|
||||
Assert.assertFalse(user.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void callingLoginShouldNotReturnUserObjectWhenGivenNullPassword() {
|
||||
Optional<User> user = userService.login("testusername", null);
|
||||
Assert.assertFalse(user.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void callingLoginShouldLookupUserByName() {
|
||||
userService.login("test", "password");
|
||||
Mockito.verify(userDAO).findByName("test");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void callingLoginShouldLookupUserByEmailIfLookupByNameFailed() {
|
||||
Mockito.when(userDAO.findByName("test@test.com")).thenReturn(null);
|
||||
userService.login("test@test.com", "password");
|
||||
Mockito.verify(userDAO).findByEmail("test@test.com");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void callingLoginShouldNotReturnUserObjectIfCouldNotFindUserByNameOrEmail() {
|
||||
Mockito.when(userDAO.findByName("test@test.com")).thenReturn(null);
|
||||
Mockito.when(userDAO.findByEmail("test@test.com")).thenReturn(null);
|
||||
|
||||
Optional<User> user = userService.login("test@test.com", "password");
|
||||
|
||||
Assert.assertFalse(user.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void callingLoginShouldNotReturnUserObjectIfUserIsDisabled() {
|
||||
Mockito.when(userDAO.findByName("test")).thenReturn(disabledUser);
|
||||
Optional<User> user = userService.login("test", "password");
|
||||
Assert.assertFalse(user.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void callingLoginShouldTryToAuthenticateUserWhoIsNotDisabled() {
|
||||
Mockito.when(userDAO.findByName("test")).thenReturn(normalUser);
|
||||
Mockito.when(passwordEncryptionService.authenticate(Mockito.anyString(), Mockito.any(byte[].class), Mockito.any(byte[].class)))
|
||||
.thenReturn(false);
|
||||
|
||||
userService.login("test", "password");
|
||||
|
||||
Mockito.verify(passwordEncryptionService).authenticate("password", ENCRYPTED_PASSWORD, SALT);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void callingLoginShouldNotReturnUserObjectOnUnsuccessfulAuthentication() {
|
||||
Mockito.when(userDAO.findByName("test")).thenReturn(normalUser);
|
||||
Mockito.when(passwordEncryptionService.authenticate(Mockito.anyString(), Mockito.any(byte[].class), Mockito.any(byte[].class)))
|
||||
.thenReturn(false);
|
||||
|
||||
Optional<User> authenticatedUser = userService.login("test", "password");
|
||||
|
||||
Assert.assertFalse(authenticatedUser.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void callingLoginShouldExecutePostLoginActivitiesForUserOnSuccessfulAuthentication() {
|
||||
Mockito.when(userDAO.findByName("test")).thenReturn(normalUser);
|
||||
Mockito.when(passwordEncryptionService.authenticate(Mockito.anyString(), Mockito.any(byte[].class), Mockito.any(byte[].class)))
|
||||
.thenReturn(true);
|
||||
Mockito.doNothing().when(postLoginActivities).executeFor(Mockito.any(User.class));
|
||||
|
||||
userService.login("test", "password");
|
||||
|
||||
Mockito.verify(postLoginActivities).executeFor(normalUser);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void callingLoginShouldReturnUserObjectOnSuccessfulAuthentication() {
|
||||
Mockito.when(userDAO.findByName("test")).thenReturn(normalUser);
|
||||
Mockito.when(passwordEncryptionService.authenticate(Mockito.anyString(), Mockito.any(byte[].class), Mockito.any(byte[].class)))
|
||||
.thenReturn(true);
|
||||
Mockito.doNothing().when(postLoginActivities).executeFor(Mockito.any(User.class));
|
||||
|
||||
Optional<User> authenticatedUser = userService.login("test", "password");
|
||||
|
||||
Assert.assertTrue(authenticatedUser.isPresent());
|
||||
Assert.assertEquals(normalUser, authenticatedUser.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void apiLoginShouldNotReturnUserIfApikeyNull() {
|
||||
Optional<User> user = userService.login(null);
|
||||
Assert.assertFalse(user.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void apiLoginShouldLookupUserByApikey() {
|
||||
Mockito.when(userDAO.findByApiKey("apikey")).thenReturn(null);
|
||||
userService.login("apikey");
|
||||
Mockito.verify(userDAO).findByApiKey("apikey");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void apiLoginShouldNotReturnUserIfUserNotFoundFromLookupByApikey() {
|
||||
Mockito.when(userDAO.findByApiKey("apikey")).thenReturn(null);
|
||||
Optional<User> user = userService.login("apikey");
|
||||
Assert.assertFalse(user.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void apiLoginShouldNotReturnUserIfUserFoundFromApikeyLookupIsDisabled() {
|
||||
Mockito.when(userDAO.findByApiKey("apikey")).thenReturn(disabledUser);
|
||||
Optional<User> user = userService.login("apikey");
|
||||
Assert.assertFalse(user.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void apiLoginShouldPerformPostLoginActivitiesIfUserFoundFromApikeyLookupNotDisabled() {
|
||||
Mockito.when(userDAO.findByApiKey("apikey")).thenReturn(normalUser);
|
||||
userService.login("apikey");
|
||||
Mockito.verify(postLoginActivities).executeFor(normalUser);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void apiLoginShouldReturnUserIfUserFoundFromApikeyLookupNotDisabled() {
|
||||
Mockito.when(userDAO.findByApiKey("apikey")).thenReturn(normalUser);
|
||||
Optional<User> returnedUser = userService.login("apikey");
|
||||
Assert.assertEquals(normalUser, returnedUser.get());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,33 +1,33 @@
|
||||
package com.commafeed.frontend.auth;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import com.commafeed.backend.model.User;
|
||||
import com.commafeed.backend.service.UserService;
|
||||
import com.commafeed.backend.service.internal.PostLoginActivities;
|
||||
import com.commafeed.frontend.session.SessionHelper;
|
||||
|
||||
public class SecurityCheckFactoryTest {
|
||||
|
||||
@Test
|
||||
public void cookieLoginShouldPerformPostLoginActivities() {
|
||||
User userInSession = new User();
|
||||
|
||||
SessionHelper sessionHelper = Mockito.mock(SessionHelper.class);
|
||||
Mockito.when(sessionHelper.getLoggedInUser()).thenReturn(Optional.of(userInSession));
|
||||
|
||||
PostLoginActivities postLoginActivities = Mockito.mock(PostLoginActivities.class);
|
||||
|
||||
UserService service = new UserService(null, null, null, null, null, null, null, postLoginActivities);
|
||||
|
||||
SecurityCheckFactory factory = new SecurityCheckFactory(null, false);
|
||||
factory.userService = service;
|
||||
factory.cookieSessionLogin(sessionHelper);
|
||||
|
||||
Mockito.verify(postLoginActivities).executeFor(userInSession);
|
||||
}
|
||||
|
||||
}
|
||||
package com.commafeed.frontend.auth;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import com.commafeed.backend.model.User;
|
||||
import com.commafeed.backend.service.UserService;
|
||||
import com.commafeed.backend.service.internal.PostLoginActivities;
|
||||
import com.commafeed.frontend.session.SessionHelper;
|
||||
|
||||
public class SecurityCheckFactoryTest {
|
||||
|
||||
@Test
|
||||
public void cookieLoginShouldPerformPostLoginActivities() {
|
||||
User userInSession = new User();
|
||||
|
||||
SessionHelper sessionHelper = Mockito.mock(SessionHelper.class);
|
||||
Mockito.when(sessionHelper.getLoggedInUser()).thenReturn(Optional.of(userInSession));
|
||||
|
||||
PostLoginActivities postLoginActivities = Mockito.mock(PostLoginActivities.class);
|
||||
|
||||
UserService service = new UserService(null, null, null, null, null, null, null, postLoginActivities);
|
||||
|
||||
SecurityCheckFactory factory = new SecurityCheckFactory(null, false);
|
||||
factory.userService = service;
|
||||
factory.cookieSessionLogin(sessionHelper);
|
||||
|
||||
Mockito.verify(postLoginActivities).executeFor(userInSession);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,107 +1,107 @@
|
||||
package com.commafeed.frontend.resource;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.mockito.ArgumentMatchers;
|
||||
import org.mockito.InOrder;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import com.commafeed.backend.model.User;
|
||||
import com.commafeed.backend.model.UserRole.Role;
|
||||
import com.commafeed.backend.service.UserService;
|
||||
import com.commafeed.frontend.model.request.LoginRequest;
|
||||
import com.commafeed.frontend.model.request.RegistrationRequest;
|
||||
import com.commafeed.frontend.session.SessionHelper;
|
||||
|
||||
public class UserRestTest {
|
||||
|
||||
@Test
|
||||
public void loginShouldNotPopulateHttpSessionIfUnsuccessfull() {
|
||||
// Absent user
|
||||
Optional<User> absentUser = Optional.empty();
|
||||
|
||||
// Create UserService partial mock
|
||||
UserService service = Mockito.mock(UserService.class);
|
||||
Mockito.when(service.login("user", "password")).thenReturn(absentUser);
|
||||
|
||||
UserREST userREST = new UserREST(null, null, null, service, null, null, null);
|
||||
SessionHelper sessionHelper = Mockito.mock(SessionHelper.class);
|
||||
|
||||
LoginRequest req = new LoginRequest();
|
||||
req.setName("user");
|
||||
req.setPassword("password");
|
||||
|
||||
userREST.login(req, sessionHelper);
|
||||
|
||||
Mockito.verify(sessionHelper, Mockito.never()).setLoggedInUser(Mockito.any(User.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loginShouldPopulateHttpSessionIfSuccessfull() {
|
||||
// Create a user
|
||||
User user = new User();
|
||||
|
||||
// Create UserService mock
|
||||
UserService service = Mockito.mock(UserService.class);
|
||||
Mockito.when(service.login("user", "password")).thenReturn(Optional.of(user));
|
||||
|
||||
LoginRequest req = new LoginRequest();
|
||||
req.setName("user");
|
||||
req.setPassword("password");
|
||||
|
||||
UserREST userREST = new UserREST(null, null, null, service, null, null, null);
|
||||
SessionHelper sessionHelper = Mockito.mock(SessionHelper.class);
|
||||
|
||||
userREST.login(req, sessionHelper);
|
||||
|
||||
Mockito.verify(sessionHelper).setLoggedInUser(user);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void registerShouldRegisterAndThenLogin() {
|
||||
// Create UserService mock
|
||||
UserService service = Mockito.mock(UserService.class);
|
||||
|
||||
RegistrationRequest req = new RegistrationRequest();
|
||||
req.setName("user");
|
||||
req.setPassword("password");
|
||||
req.setEmail("test@test.com");
|
||||
|
||||
InOrder inOrder = Mockito.inOrder(service);
|
||||
|
||||
SessionHelper sessionHelper = Mockito.mock(SessionHelper.class);
|
||||
UserREST userREST = new UserREST(null, null, null, service, null, null, null);
|
||||
|
||||
userREST.registerUser(req, sessionHelper);
|
||||
|
||||
inOrder.verify(service).register("user", "password", "test@test.com", Arrays.asList(Role.USER));
|
||||
inOrder.verify(service).login("user", "password");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void registerShouldPopulateHttpSession() {
|
||||
// Create a user
|
||||
User user = new User();
|
||||
|
||||
// Create UserService mock
|
||||
UserService service = Mockito.mock(UserService.class);
|
||||
Mockito.when(service.register(Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class),
|
||||
ArgumentMatchers.anyList())).thenReturn(user);
|
||||
Mockito.when(service.login(Mockito.any(String.class), Mockito.any(String.class))).thenReturn(Optional.of(user));
|
||||
|
||||
RegistrationRequest req = new RegistrationRequest();
|
||||
req.setName("user");
|
||||
req.setPassword("password");
|
||||
req.setEmail("test@test.com");
|
||||
|
||||
SessionHelper sessionHelper = Mockito.mock(SessionHelper.class);
|
||||
UserREST userREST = new UserREST(null, null, null, service, null, null, null);
|
||||
|
||||
userREST.registerUser(req, sessionHelper);
|
||||
|
||||
Mockito.verify(sessionHelper).setLoggedInUser(user);
|
||||
}
|
||||
|
||||
}
|
||||
package com.commafeed.frontend.resource;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.mockito.ArgumentMatchers;
|
||||
import org.mockito.InOrder;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import com.commafeed.backend.model.User;
|
||||
import com.commafeed.backend.model.UserRole.Role;
|
||||
import com.commafeed.backend.service.UserService;
|
||||
import com.commafeed.frontend.model.request.LoginRequest;
|
||||
import com.commafeed.frontend.model.request.RegistrationRequest;
|
||||
import com.commafeed.frontend.session.SessionHelper;
|
||||
|
||||
public class UserRestTest {
|
||||
|
||||
@Test
|
||||
public void loginShouldNotPopulateHttpSessionIfUnsuccessfull() {
|
||||
// Absent user
|
||||
Optional<User> absentUser = Optional.empty();
|
||||
|
||||
// Create UserService partial mock
|
||||
UserService service = Mockito.mock(UserService.class);
|
||||
Mockito.when(service.login("user", "password")).thenReturn(absentUser);
|
||||
|
||||
UserREST userREST = new UserREST(null, null, null, service, null, null, null);
|
||||
SessionHelper sessionHelper = Mockito.mock(SessionHelper.class);
|
||||
|
||||
LoginRequest req = new LoginRequest();
|
||||
req.setName("user");
|
||||
req.setPassword("password");
|
||||
|
||||
userREST.login(req, sessionHelper);
|
||||
|
||||
Mockito.verify(sessionHelper, Mockito.never()).setLoggedInUser(Mockito.any(User.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loginShouldPopulateHttpSessionIfSuccessfull() {
|
||||
// Create a user
|
||||
User user = new User();
|
||||
|
||||
// Create UserService mock
|
||||
UserService service = Mockito.mock(UserService.class);
|
||||
Mockito.when(service.login("user", "password")).thenReturn(Optional.of(user));
|
||||
|
||||
LoginRequest req = new LoginRequest();
|
||||
req.setName("user");
|
||||
req.setPassword("password");
|
||||
|
||||
UserREST userREST = new UserREST(null, null, null, service, null, null, null);
|
||||
SessionHelper sessionHelper = Mockito.mock(SessionHelper.class);
|
||||
|
||||
userREST.login(req, sessionHelper);
|
||||
|
||||
Mockito.verify(sessionHelper).setLoggedInUser(user);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void registerShouldRegisterAndThenLogin() {
|
||||
// Create UserService mock
|
||||
UserService service = Mockito.mock(UserService.class);
|
||||
|
||||
RegistrationRequest req = new RegistrationRequest();
|
||||
req.setName("user");
|
||||
req.setPassword("password");
|
||||
req.setEmail("test@test.com");
|
||||
|
||||
InOrder inOrder = Mockito.inOrder(service);
|
||||
|
||||
SessionHelper sessionHelper = Mockito.mock(SessionHelper.class);
|
||||
UserREST userREST = new UserREST(null, null, null, service, null, null, null);
|
||||
|
||||
userREST.registerUser(req, sessionHelper);
|
||||
|
||||
inOrder.verify(service).register("user", "password", "test@test.com", Arrays.asList(Role.USER));
|
||||
inOrder.verify(service).login("user", "password");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void registerShouldPopulateHttpSession() {
|
||||
// Create a user
|
||||
User user = new User();
|
||||
|
||||
// Create UserService mock
|
||||
UserService service = Mockito.mock(UserService.class);
|
||||
Mockito.when(service.register(Mockito.any(String.class), Mockito.any(String.class), Mockito.any(String.class),
|
||||
ArgumentMatchers.anyList())).thenReturn(user);
|
||||
Mockito.when(service.login(Mockito.any(String.class), Mockito.any(String.class))).thenReturn(Optional.of(user));
|
||||
|
||||
RegistrationRequest req = new RegistrationRequest();
|
||||
req.setName("user");
|
||||
req.setPassword("password");
|
||||
req.setEmail("test@test.com");
|
||||
|
||||
SessionHelper sessionHelper = Mockito.mock(SessionHelper.class);
|
||||
UserREST userREST = new UserREST(null, null, null, service, null, null, null);
|
||||
|
||||
userREST.registerUser(req, sessionHelper);
|
||||
|
||||
Mockito.verify(sessionHelper).setLoggedInUser(user);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user