apply formatter

This commit is contained in:
Athou
2013-07-25 09:17:33 +02:00
parent 02f1090fe7
commit 8845c54d0c
82 changed files with 626 additions and 1116 deletions

View File

@@ -1,6 +1,5 @@
package com.commafeed.frontend.rest;
public class Enums {
public enum Type {

View File

@@ -17,18 +17,14 @@ import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
public class JsonProvider extends JacksonJsonProvider {
@Override
public void writeTo(Object value, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders,
OutputStream entityStream) throws IOException {
public void writeTo(Object value, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException {
httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, mediaType.toString()
+ ";charset=UTF-8");
httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, mediaType.toString() + ";charset=UTF-8");
httpHeaders.putSingle(HttpHeaders.CACHE_CONTROL, "no-cache");
httpHeaders.putSingle(HttpHeaders.PRAGMA, "no-cache");
super.writeTo(value, type, genericType, annotations, mediaType,
httpHeaders, entityStream);
super.writeTo(value, type, genericType, annotations, mediaType, httpHeaders, entityStream);
}
}

View File

@@ -51,8 +51,7 @@ public abstract class AbstractREST {
ServletWebResponse swresp = new ServletWebResponse(swreq, response);
RequestCycle cycle = app.createRequestCycle(swreq, swresp);
ThreadContext.setRequestCycle(cycle);
CommaFeedSession session = (CommaFeedSession) app
.fetchCreateAndSetSession(cycle);
CommaFeedSession session = (CommaFeedSession) app.fetchCreateAndSetSession(cycle);
if (session.getUser() == null) {
cookieLogin(app, session);
@@ -63,8 +62,7 @@ public abstract class AbstractREST {
}
private void cookieLogin(CommaFeedApplication app, CommaFeedSession session) {
IAuthenticationStrategy authenticationStrategy = app
.getSecuritySettings().getAuthenticationStrategy();
IAuthenticationStrategy authenticationStrategy = app.getSecuritySettings().getAuthenticationStrategy();
String[] data = authenticationStrategy.load();
if (data != null && data.length > 1) {
session.signIn(data[0], data[1]);
@@ -98,8 +96,7 @@ public abstract class AbstractREST {
boolean allowed = true;
User user = null;
Method method = context.getMethod();
SecurityCheck check = method.isAnnotationPresent(SecurityCheck.class) ? method
.getAnnotation(SecurityCheck.class) : method
SecurityCheck check = method.isAnnotationPresent(SecurityCheck.class) ? method.getAnnotation(SecurityCheck.class) : method
.getDeclaringClass().getAnnotation(SecurityCheck.class);
if (check != null) {
@@ -113,11 +110,9 @@ public abstract class AbstractREST {
}
if (!allowed) {
if (user == null) {
return Response.status(Status.UNAUTHORIZED)
.entity("You are not authorized to do this.").build();
return Response.status(Status.UNAUTHORIZED).entity("You are not authorized to do this.").build();
} else {
return Response.status(Status.FORBIDDEN)
.entity("You are not authorized to do this.").build();
return Response.status(Status.FORBIDDEN).entity("You are not authorized to do this.").build();
}
}

View File

@@ -33,40 +33,33 @@ public abstract class AbstractResourceREST extends AbstractREST {
@GET
@SecurityCheck(value = Role.NONE)
@ApiOperation(value = "Returns information about API parameters", responseClass = "com.wordnik.swagger.core.Documentation")
public Response getHelp(@Context Application app,
@Context HttpHeaders headers, @Context UriInfo uriInfo) {
public Response getHelp(@Context Application app, @Context HttpHeaders headers, @Context UriInfo uriInfo) {
TypeUtil.addAllowablePackage(Entries.class.getPackage().getName());
TypeUtil.addAllowablePackage(MarkRequest.class.getPackage().getName());
String apiVersion = ApiDocumentationREST.API_VERSION;
String swaggerVersion = SwaggerSpec.version();
String basePath = ApiDocumentationREST
.getBasePath(applicationSettingsService.get().getPublicUrl());
String basePath = ApiDocumentationREST.getBasePath(applicationSettingsService.get().getPublicUrl());
Class<?> resource = null;
String path = prependSlash(uriInfo.getPath());
for (Class<?> klass : app.getClasses()) {
Api api = klass.getAnnotation(Api.class);
if (api != null && api.value() != null
&& StringUtils.equals(prependSlash(api.value()), path)) {
if (api != null && api.value() != null && StringUtils.equals(prependSlash(api.value()), path)) {
resource = klass;
break;
}
}
if (resource == null) {
return Response
.status(Status.NOT_FOUND)
.entity("Api annotation not found on class "
+ getClass().getName()).build();
return Response.status(Status.NOT_FOUND).entity("Api annotation not found on class " + getClass().getName()).build();
}
Api api = resource.getAnnotation(Api.class);
String apiPath = api.value();
String apiListingPath = api.value();
Documentation doc = new HelpApi(null).filterDocs(JaxrsApiReader.read(
resource, apiVersion, swaggerVersion, basePath, apiPath),
Documentation doc = new HelpApi(null).filterDocs(JaxrsApiReader.read(resource, apiVersion, swaggerVersion, basePath, apiPath),
headers, uriInfo, apiListingPath, apiPath);
doc.setSwaggerVersion(swaggerVersion);

View File

@@ -102,24 +102,18 @@ public class AdminREST extends AbstractResourceREST {
roles.add(Role.ADMIN);
}
try {
userService.register(userModel.getName(),
userModel.getPassword(), userModel.getEmail(), roles,
true);
userService.register(userModel.getName(), userModel.getPassword(), userModel.getEmail(), roles, true);
} catch (Exception e) {
return Response.status(Status.CONFLICT).entity(e.getMessage())
.build();
return Response.status(Status.CONFLICT).entity(e.getMessage()).build();
}
} else {
User user = userDAO.findById(id);
if (StartupBean.USERNAME_ADMIN.equals(user.getName())
&& !userModel.isEnabled()) {
return Response.status(Status.FORBIDDEN)
.entity("You cannot disable the admin user.").build();
if (StartupBean.USERNAME_ADMIN.equals(user.getName()) && !userModel.isEnabled()) {
return Response.status(Status.FORBIDDEN).entity("You cannot disable the admin user.").build();
}
user.setName(userModel.getName());
if (StringUtils.isNotBlank(userModel.getPassword())) {
user.setPassword(encryptionService.getEncryptedPassword(
userModel.getPassword(), user.getSalt()));
user.setPassword(encryptionService.getEncryptedPassword(userModel.getPassword(), user.getSalt()));
}
user.setEmail(userModel.getEmail());
user.setDisabled(!userModel.isEnabled());
@@ -130,10 +124,7 @@ public class AdminREST extends AbstractResourceREST {
userRoleDAO.saveOrUpdate(new UserRole(user, Role.ADMIN));
} else if (!userModel.isAdmin() && roles.contains(Role.ADMIN)) {
if (StartupBean.USERNAME_ADMIN.equals(user.getName())) {
return Response
.status(Status.FORBIDDEN)
.entity("You cannot remove the admin role from the admin user.")
.build();
return Response.status(Status.FORBIDDEN).entity("You cannot remove the admin role from the admin user.").build();
}
for (UserRole userRole : userRoleDAO.findAll(user)) {
if (userRole.getRole() == Role.ADMIN) {
@@ -150,8 +141,7 @@ public class AdminREST extends AbstractResourceREST {
@Path("/user/get/{id}")
@GET
@ApiOperation(value = "Get user information", notes = "Get user information", responseClass = "com.commafeed.frontend.model.UserModel")
public Response getUser(
@ApiParam(value = "user id", required = true) @PathParam("id") Long id) {
public Response getUser(@ApiParam(value = "user id", required = true) @PathParam("id") Long id) {
Preconditions.checkNotNull(id);
User user = userDAO.findById(id);
UserModel userModel = new UserModel();
@@ -205,8 +195,7 @@ public class AdminREST extends AbstractResourceREST {
return Response.status(Status.NOT_FOUND).build();
}
if (StartupBean.USERNAME_ADMIN.equals(user.getName())) {
return Response.status(Status.FORBIDDEN)
.entity("You cannot delete the admin user.").build();
return Response.status(Status.FORBIDDEN).entity("You cannot delete the admin user.").build();
}
userService.unregister(user);
return Response.ok().build();
@@ -214,7 +203,10 @@ public class AdminREST extends AbstractResourceREST {
@Path("/settings")
@GET
@ApiOperation(value = "Retrieve application settings", notes = "Retrieve application settings", responseClass = "com.commafeed.backend.model.ApplicationSettings")
@ApiOperation(
value = "Retrieve application settings",
notes = "Retrieve application settings",
responseClass = "com.commafeed.backend.model.ApplicationSettings")
public Response getSettings() {
return Response.ok(applicationSettingsService.get()).build();
}
@@ -222,8 +214,7 @@ public class AdminREST extends AbstractResourceREST {
@Path("/settings")
@POST
@ApiOperation(value = "Save application settings", notes = "Save application settings")
public Response saveSettings(
@ApiParam(required = true) ApplicationSettings settings) {
public Response saveSettings(@ApiParam(required = true) ApplicationSettings settings) {
Preconditions.checkNotNull(settings);
applicationSettingsService.save(settings);
return Response.ok().build();
@@ -232,8 +223,7 @@ public class AdminREST extends AbstractResourceREST {
@Path("/metrics")
@GET
@ApiOperation(value = "Retrieve server metrics")
public Response getMetrics(
@QueryParam("backlog") @DefaultValue("false") boolean backlog) {
public Response getMetrics(@QueryParam("backlog") @DefaultValue("false") boolean backlog) {
Map<String, Object> map = Maps.newLinkedHashMap();
map.put("lastMinute", metricsBean.getLastMinute());
map.put("lastHour", metricsBean.getLastHour());
@@ -254,52 +244,44 @@ public class AdminREST extends AbstractResourceREST {
@ApiOperation(value = "Feeds cleanup", notes = "Delete feeds without subscriptions and entries without feeds")
public Response cleanupFeeds() {
Map<String, Long> map = Maps.newHashMap();
map.put("feeds_without_subscriptions",
cleaner.cleanFeedsWithoutSubscriptions());
map.put("feeds_without_subscriptions", cleaner.cleanFeedsWithoutSubscriptions());
return Response.ok(map).build();
}
@Path("/cleanup/content")
@GET
@ApiOperation(value = "Content cleanup", notes = "Delete contents without entries")
public Response cleanupContents() {
Map<String, Long> map = Maps.newHashMap();
map.put("contents_without_entries",
cleaner.cleanContentsWithoutEntries());
map.put("contents_without_entries", cleaner.cleanContentsWithoutEntries());
return Response.ok(map).build();
}
@Path("/cleanup/entries")
@GET
@ApiOperation(value = "Entries cleanup", notes = "Delete entries older than given date")
public Response cleanupEntries(
@QueryParam("days") @DefaultValue("30") int days) {
public Response cleanupEntries(@QueryParam("days") @DefaultValue("30") int days) {
Map<String, Long> map = Maps.newHashMap();
map.put("old entries",
cleaner.cleanEntriesOlderThan(days, TimeUnit.DAYS));
map.put("old entries", cleaner.cleanEntriesOlderThan(days, TimeUnit.DAYS));
return Response.ok(map).build();
}
@Path("/cleanup/findDuplicateFeeds")
@GET
@ApiOperation(value = "Find duplicate feeds")
public Response findDuplicateFeeds(@QueryParam("mode") DuplicateMode mode,
@QueryParam("page") int page, @QueryParam("limit") int limit,
@QueryParam("minCount") long minCount) {
List<FeedCount> list = feedDAO.findDuplicates(mode, limit * page,
limit, minCount);
public Response findDuplicateFeeds(@QueryParam("mode") DuplicateMode mode, @QueryParam("page") int page,
@QueryParam("limit") int limit, @QueryParam("minCount") long minCount) {
List<FeedCount> list = feedDAO.findDuplicates(mode, limit * page, limit, minCount);
return Response.ok(list).build();
}
@Path("/cleanup/merge")
@POST
@ApiOperation(value = "Merge feeds", notes = "Merge feeds together")
public Response mergeFeeds(
@ApiParam(required = true) FeedMergeRequest request) {
public Response mergeFeeds(@ApiParam(required = true) FeedMergeRequest request) {
Feed into = feedDAO.findById(request.getIntoFeedId());
if (into == null) {
return Response.status(Status.BAD_REQUEST)
.entity("'into feed' not found").build();
return Response.status(Status.BAD_REQUEST).entity("'into feed' not found").build();
}
List<Feed> feeds = Lists.newArrayList();
@@ -309,8 +291,7 @@ public class AdminREST extends AbstractResourceREST {
}
if (feeds.isEmpty()) {
return Response.status(Status.BAD_REQUEST)
.entity("'from feeds' empty").build();
return Response.status(Status.BAD_REQUEST).entity("'from feeds' empty").build();
}
cleaner.mergeFeeds(into, feeds);

View File

@@ -40,14 +40,12 @@ public class ApiDocumentationREST extends AbstractREST {
}
Api api = resource.getAnnotation(Api.class);
if (api != null) {
doc.addApi(new DocumentationEndPoint(api.value(), api
.description()));
doc.addApi(new DocumentationEndPoint(api.value(), api.description()));
}
}
doc.setSwaggerVersion(SwaggerSpec.version());
doc.setBasePath(getBasePath(applicationSettingsService.get()
.getPublicUrl()));
doc.setBasePath(getBasePath(applicationSettingsService.get().getPublicUrl()));
doc.setApiVersion(API_VERSION);
return Response.ok().entity(doc).build();

View File

@@ -82,14 +82,20 @@ public class CategoryREST extends AbstractResourceREST {
@Path("/entries")
@GET
@ApiOperation(value = "Get category entries", notes = "Get a list of category entries", responseClass = "com.commafeed.frontend.model.Entries")
@ApiOperation(
value = "Get category entries",
notes = "Get a list of category entries",
responseClass = "com.commafeed.frontend.model.Entries")
public Response getCategoryEntries(
@ApiParam(value = "id of the category, 'all' or 'starred'", required = true) @QueryParam("id") String id,
@ApiParam(value = "all entries or only unread ones", allowableValues = "all,unread", required = true) @DefaultValue("unread") @QueryParam("readType") ReadType readType,
@ApiParam(value = "only entries newer than this") @QueryParam("newerThan") Long newerThan,
@ApiParam(value = "offset for paging") @DefaultValue("0") @QueryParam("offset") int offset,
@ApiParam(value = "limit for paging, default 20, maximum 50") @DefaultValue("20") @QueryParam("limit") int limit,
@ApiParam(value = "date ordering", allowableValues = "asc,desc") @QueryParam("order") @DefaultValue("desc") ReadingOrder order) {
@ApiParam(value = "id of the category, 'all' or 'starred'", required = true) @QueryParam("id") String id, @ApiParam(
value = "all entries or only unread ones",
allowableValues = "all,unread",
required = true) @DefaultValue("unread") @QueryParam("readType") ReadType readType, @ApiParam(
value = "only entries newer than this") @QueryParam("newerThan") Long newerThan,
@ApiParam(value = "offset for paging") @DefaultValue("0") @QueryParam("offset") int offset, @ApiParam(
value = "limit for paging, default 20, maximum 50") @DefaultValue("20") @QueryParam("limit") int limit, @ApiParam(
value = "date ordering",
allowableValues = "asc,desc") @QueryParam("order") @DefaultValue("desc") ReadingOrder order) {
Preconditions.checkNotNull(readType);
limit = Math.min(limit, 50);
@@ -101,50 +107,38 @@ public class CategoryREST extends AbstractResourceREST {
id = ALL;
}
Date newerThanDate = newerThan == null ? null : new Date(
Long.valueOf(newerThan));
Date newerThanDate = newerThan == null ? null : new Date(Long.valueOf(newerThan));
if (ALL.equals(id)) {
entries.setName("All");
List<FeedSubscription> subscriptions = feedSubscriptionDAO
.findAll(getUser());
List<FeedEntryStatus> list = feedEntryStatusDAO
.findBySubscriptions(subscriptions, unreadOnly, null,
newerThanDate, offset, limit + 1, order, true);
List<FeedSubscription> subscriptions = feedSubscriptionDAO.findAll(getUser());
List<FeedEntryStatus> list = feedEntryStatusDAO.findBySubscriptions(subscriptions, unreadOnly, null, newerThanDate, offset,
limit + 1, order, true);
for (FeedEntryStatus status : list) {
entries.getEntries().add(
Entry.build(status, applicationSettingsService.get()
.getPublicUrl(), applicationSettingsService
.get().isImageProxyEnabled()));
Entry.build(status, applicationSettingsService.get().getPublicUrl(), applicationSettingsService.get()
.isImageProxyEnabled()));
}
} else if (STARRED.equals(id)) {
entries.setName("Starred");
List<FeedEntryStatus> starred = feedEntryStatusDAO.findStarred(
getUser(), newerThanDate, offset, limit + 1, order, true);
List<FeedEntryStatus> starred = feedEntryStatusDAO.findStarred(getUser(), newerThanDate, offset, limit + 1, order, true);
for (FeedEntryStatus status : starred) {
entries.getEntries().add(
Entry.build(status, applicationSettingsService.get()
.getPublicUrl(), applicationSettingsService
.get().isImageProxyEnabled()));
Entry.build(status, applicationSettingsService.get().getPublicUrl(), applicationSettingsService.get()
.isImageProxyEnabled()));
}
} else {
FeedCategory parent = feedCategoryDAO.findById(getUser(),
Long.valueOf(id));
FeedCategory parent = feedCategoryDAO.findById(getUser(), Long.valueOf(id));
if (parent != null) {
List<FeedCategory> categories = feedCategoryDAO
.findAllChildrenCategories(getUser(), parent);
List<FeedSubscription> subs = feedSubscriptionDAO
.findByCategories(getUser(), categories);
List<FeedEntryStatus> list = feedEntryStatusDAO
.findBySubscriptions(subs, unreadOnly, null,
newerThanDate, offset, limit + 1, order, true);
List<FeedCategory> categories = feedCategoryDAO.findAllChildrenCategories(getUser(), parent);
List<FeedSubscription> subs = feedSubscriptionDAO.findByCategories(getUser(), categories);
List<FeedEntryStatus> list = feedEntryStatusDAO.findBySubscriptions(subs, unreadOnly, null, newerThanDate, offset,
limit + 1, order, true);
for (FeedEntryStatus status : list) {
entries.getEntries().add(
Entry.build(status, applicationSettingsService
.get().getPublicUrl(),
applicationSettingsService.get()
.isImageProxyEnabled()));
Entry.build(status, applicationSettingsService.get().getPublicUrl(), applicationSettingsService.get()
.isImageProxyEnabled()));
}
entries.setName(parent.getName());
}
@@ -176,8 +170,7 @@ public class CategoryREST extends AbstractResourceREST {
int offset = 0;
int limit = 20;
Entries entries = (Entries) getCategoryEntries(id, readType, null,
offset, limit, order).getEntity();
Entries entries = (Entries) getCategoryEntries(id, readType, null, offset, limit, order).getEntity();
SyndFeed feed = new SyndFeedImpl();
feed.setFeedType("rss_2.0");
@@ -206,28 +199,21 @@ public class CategoryREST extends AbstractResourceREST {
@Path("/mark")
@POST
@ApiOperation(value = "Mark category entries", notes = "Mark feed entries of this category as read")
public Response markCategoryEntries(
@ApiParam(value = "category id, or 'all'", required = true) MarkRequest req) {
public Response markCategoryEntries(@ApiParam(value = "category id, or 'all'", required = true) MarkRequest req) {
Preconditions.checkNotNull(req);
Preconditions.checkNotNull(req.getId());
Date olderThan = req.getOlderThan() == null ? null : new Date(
req.getOlderThan());
Date olderThan = req.getOlderThan() == null ? null : new Date(req.getOlderThan());
if (ALL.equals(req.getId())) {
List<FeedSubscription> subscriptions = feedSubscriptionDAO
.findAll(getUser());
feedEntryStatusDAO
.markSubscriptionEntries(subscriptions, olderThan);
List<FeedSubscription> subscriptions = feedSubscriptionDAO.findAll(getUser());
feedEntryStatusDAO.markSubscriptionEntries(subscriptions, olderThan);
} else if (STARRED.equals(req.getId())) {
feedEntryStatusDAO.markStarredEntries(getUser(), olderThan);
} else {
FeedCategory parent = feedCategoryDAO.findById(getUser(),
Long.valueOf(req.getId()));
List<FeedCategory> categories = feedCategoryDAO
.findAllChildrenCategories(getUser(), parent);
List<FeedSubscription> subs = feedSubscriptionDAO.findByCategories(
getUser(), categories);
FeedCategory parent = feedCategoryDAO.findById(getUser(), Long.valueOf(req.getId()));
List<FeedCategory> categories = feedCategoryDAO.findAllChildrenCategories(getUser(), parent);
List<FeedSubscription> subs = feedSubscriptionDAO.findByCategories(getUser(), categories);
feedEntryStatusDAO.markSubscriptionEntries(subs, olderThan);
}
cache.invalidateUserData(getUser());
@@ -237,8 +223,7 @@ public class CategoryREST extends AbstractResourceREST {
@Path("/add")
@POST
@ApiOperation(value = "Add a category", notes = "Add a new feed category")
public Response addCategory(
@ApiParam(required = true) AddCategoryRequest req) {
public Response addCategory(@ApiParam(required = true) AddCategoryRequest req) {
Preconditions.checkNotNull(req);
Preconditions.checkNotNull(req.getName());
@@ -267,17 +252,14 @@ public class CategoryREST extends AbstractResourceREST {
FeedCategory cat = feedCategoryDAO.findById(getUser(), req.getId());
if (cat != null) {
List<FeedSubscription> subs = feedSubscriptionDAO.findByCategory(
getUser(), cat);
List<FeedSubscription> subs = feedSubscriptionDAO.findByCategory(getUser(), cat);
for (FeedSubscription sub : subs) {
sub.setCategory(null);
}
feedSubscriptionDAO.saveOrUpdate(subs);
List<FeedCategory> categories = feedCategoryDAO
.findAllChildrenCategories(getUser(), cat);
List<FeedCategory> categories = feedCategoryDAO.findAllChildrenCategories(getUser(), cat);
for (FeedCategory child : categories) {
if (!child.getId().equals(cat.getId())
&& child.getParent().getId().equals(cat.getId())) {
if (!child.getId().equals(cat.getId()) && child.getParent().getId().equals(cat.getId())) {
child.setParent(null);
}
}
@@ -294,43 +276,35 @@ public class CategoryREST extends AbstractResourceREST {
@POST
@Path("/modify")
@ApiOperation(value = "Rename a category", notes = "Rename an existing feed category")
public Response modifyCategory(
@ApiParam(required = true) CategoryModificationRequest req) {
public Response modifyCategory(@ApiParam(required = true) CategoryModificationRequest req) {
Preconditions.checkNotNull(req);
Preconditions.checkNotNull(req.getId());
FeedCategory category = feedCategoryDAO
.findById(getUser(), req.getId());
FeedCategory category = feedCategoryDAO.findById(getUser(), req.getId());
if (StringUtils.isNotBlank(req.getName())) {
category.setName(req.getName());
}
FeedCategory parent = null;
if (req.getParentId() != null
&& !CategoryREST.ALL.equals(req.getParentId())
&& !StringUtils.equals(req.getParentId(),
String.valueOf(req.getId()))) {
parent = feedCategoryDAO.findById(getUser(),
Long.valueOf(req.getParentId()));
if (req.getParentId() != null && !CategoryREST.ALL.equals(req.getParentId())
&& !StringUtils.equals(req.getParentId(), String.valueOf(req.getId()))) {
parent = feedCategoryDAO.findById(getUser(), Long.valueOf(req.getParentId()));
}
category.setParent(parent);
if (req.getPosition() != null) {
List<FeedCategory> categories = feedCategoryDAO.findByParent(
getUser(), parent);
List<FeedCategory> categories = feedCategoryDAO.findByParent(getUser(), parent);
Collections.sort(categories, new Comparator<FeedCategory>() {
@Override
public int compare(FeedCategory o1, FeedCategory o2) {
return ObjectUtils.compare(o1.getPosition(),
o2.getPosition());
return ObjectUtils.compare(o1.getPosition(), o2.getPosition());
}
});
int existingIndex = -1;
for (int i = 0; i < categories.size(); i++) {
if (ObjectUtils.equals(categories.get(i).getId(),
category.getId())) {
if (ObjectUtils.equals(categories.get(i).getId(), category.getId())) {
existingIndex = i;
}
}
@@ -338,8 +312,7 @@ public class CategoryREST extends AbstractResourceREST {
categories.remove(existingIndex);
}
categories.add(Math.min(req.getPosition(), categories.size()),
category);
categories.add(Math.min(req.getPosition(), categories.size()), category);
for (int i = 0; i < categories.size(); i++) {
categories.get(i).setPosition(i);
}
@@ -360,8 +333,7 @@ public class CategoryREST extends AbstractResourceREST {
Preconditions.checkNotNull(req);
Preconditions.checkNotNull(req.getId());
FeedCategory category = feedCategoryDAO.findById(getUser(),
Long.valueOf(req.getId()));
FeedCategory category = feedCategoryDAO.findById(getUser(), Long.valueOf(req.getId()));
if (category == null) {
return Response.status(Status.NOT_FOUND).build();
}
@@ -376,8 +348,7 @@ public class CategoryREST extends AbstractResourceREST {
@ApiOperation(value = "Get unread count for feed subscriptions", responseClass = "List[com.commafeed.frontend.model.UnreadCount]")
public Response getUnreadCount() {
List<UnreadCount> list = Lists.newArrayList();
Map<Long, Long> unreadCount = feedSubscriptionService
.getUnreadCount(getUser());
Map<Long, Long> unreadCount = feedSubscriptionService.getUnreadCount(getUser());
for (Map.Entry<Long, Long> e : unreadCount.entrySet()) {
list.add(new UnreadCount(e.getKey(), e.getValue()));
}
@@ -386,7 +357,10 @@ public class CategoryREST extends AbstractResourceREST {
@GET
@Path("/get")
@ApiOperation(value = "Get feed categories", notes = "Get all categories and subscriptions of the user", responseClass = "com.commafeed.frontend.model.Category")
@ApiOperation(
value = "Get feed categories",
notes = "Get all categories and subscriptions of the user",
responseClass = "com.commafeed.frontend.model.Category")
public Response getSubscriptions() {
User user = getUser();
@@ -394,10 +368,8 @@ public class CategoryREST extends AbstractResourceREST {
if (root == null) {
log.debug("root category cache miss for {}", user.getName());
List<FeedCategory> categories = feedCategoryDAO.findAll(user);
List<FeedSubscription> subscriptions = feedSubscriptionDAO
.findAll(getUser());
Map<Long, Long> unreadCount = feedSubscriptionService
.getUnreadCount(getUser());
List<FeedSubscription> subscriptions = feedSubscriptionDAO.findAll(getUser());
Map<Long, Long> unreadCount = feedSubscriptionService.getUnreadCount(getUser());
root = buildCategory(null, categories, subscriptions, unreadCount);
root.setId("all");
@@ -407,18 +379,14 @@ public class CategoryREST extends AbstractResourceREST {
return Response.ok(root).build();
}
private Category buildCategory(Long id, List<FeedCategory> categories,
List<FeedSubscription> subscriptions, Map<Long, Long> unreadCount) {
private Category buildCategory(Long id, List<FeedCategory> categories, List<FeedSubscription> subscriptions, Map<Long, Long> unreadCount) {
Category category = new Category();
category.setId(String.valueOf(id));
category.setExpanded(true);
for (FeedCategory c : categories) {
if ((id == null && c.getParent() == null)
|| (c.getParent() != null && ObjectUtils.equals(c
.getParent().getId(), id))) {
Category child = buildCategory(c.getId(), categories,
subscriptions, unreadCount);
if ((id == null && c.getParent() == null) || (c.getParent() != null && ObjectUtils.equals(c.getParent().getId(), id))) {
Category child = buildCategory(c.getId(), categories, subscriptions, unreadCount);
child.setId(String.valueOf(c.getId()));
child.setName(c.getName());
child.setPosition(c.getPosition());
@@ -438,13 +406,10 @@ public class CategoryREST extends AbstractResourceREST {
for (FeedSubscription subscription : subscriptions) {
if ((id == null && subscription.getCategory() == null)
|| (subscription.getCategory() != null && ObjectUtils
.equals(subscription.getCategory().getId(), id))) {
|| (subscription.getCategory() != null && ObjectUtils.equals(subscription.getCategory().getId(), id))) {
Long size = unreadCount.get(subscription.getId());
long unread = size == null ? 0 : size;
Subscription sub = Subscription
.build(subscription, applicationSettingsService.get()
.getPublicUrl(), unread);
Subscription sub = Subscription.build(subscription, applicationSettingsService.get().getPublicUrl(), unread);
category.getFeeds().add(sub);
}
}

View File

@@ -50,14 +50,12 @@ public class EntryREST extends AbstractResourceREST {
@Path("/mark")
@POST
@ApiOperation(value = "Mark a feed entry", notes = "Mark a feed entry as read/unread")
public Response markFeedEntry(
@ApiParam(value = "Mark Request", required = true) MarkRequest req) {
public Response markFeedEntry(@ApiParam(value = "Mark Request", required = true) MarkRequest req) {
Preconditions.checkNotNull(req);
Preconditions.checkNotNull(req.getId());
Preconditions.checkNotNull(req.getFeedId());
feedEntryService.markEntry(getUser(), Long.valueOf(req.getId()),
req.getFeedId(), req.isRead());
feedEntryService.markEntry(getUser(), Long.valueOf(req.getId()), req.getFeedId(), req.isRead());
cache.invalidateUserData(getUser());
return Response.ok(Status.OK).build();
}
@@ -65,8 +63,7 @@ public class EntryREST extends AbstractResourceREST {
@Path("/markMultiple")
@POST
@ApiOperation(value = "Mark multiple feed entries", notes = "Mark feed entries as read/unread")
public Response markFeedEntries(
@ApiParam(value = "Multiple Mark Request", required = true) MultipleMarkRequest req) {
public Response markFeedEntries(@ApiParam(value = "Multiple Mark Request", required = true) MultipleMarkRequest req) {
Preconditions.checkNotNull(req);
Preconditions.checkNotNull(req.getRequests());
@@ -80,25 +77,26 @@ public class EntryREST extends AbstractResourceREST {
@Path("/star")
@POST
@ApiOperation(value = "Mark a feed entry", notes = "Mark a feed entry as read/unread")
public Response starFeedEntry(
@ApiParam(value = "Star Request", required = true) StarRequest req) {
public Response starFeedEntry(@ApiParam(value = "Star Request", required = true) StarRequest req) {
Preconditions.checkNotNull(req);
Preconditions.checkNotNull(req.getId());
Preconditions.checkNotNull(req.getFeedId());
feedEntryService.starEntry(getUser(), Long.valueOf(req.getId()),
req.getFeedId(), req.isStarred());
feedEntryService.starEntry(getUser(), Long.valueOf(req.getId()), req.getFeedId(), req.isStarred());
return Response.ok(Status.OK).build();
}
@Path("/search")
@GET
@ApiOperation(value = "Search for entries", notes = "Look through title and content of entries by keywords", responseClass = "com.commafeed.frontend.model.Entries")
@ApiOperation(
value = "Search for entries",
notes = "Look through title and content of entries by keywords",
responseClass = "com.commafeed.frontend.model.Entries")
public Response searchEntries(
@ApiParam(value = "keywords separated by spaces, 3 characters minimum", required = true) @QueryParam("keywords") String keywords,
@ApiParam(value = "offset for paging") @DefaultValue("0") @QueryParam("offset") int offset,
@ApiParam(value = "limit for paging") @DefaultValue("-1") @QueryParam("limit") int limit) {
@ApiParam(value = "offset for paging") @DefaultValue("0") @QueryParam("offset") int offset, @ApiParam(
value = "limit for paging") @DefaultValue("-1") @QueryParam("limit") int limit) {
keywords = StringUtils.trimToEmpty(keywords);
limit = Math.min(limit, 50);
Preconditions.checkArgument(StringUtils.length(keywords) >= 3);
@@ -107,12 +105,10 @@ public class EntryREST extends AbstractResourceREST {
List<Entry> list = Lists.newArrayList();
List<FeedSubscription> subs = feedSubscriptionDAO.findAll(getUser());
List<FeedEntryStatus> entriesStatus = feedEntryStatusDAO
.findBySubscriptions(subs, false, keywords, null, offset,
limit, ReadingOrder.desc, true);
List<FeedEntryStatus> entriesStatus = feedEntryStatusDAO.findBySubscriptions(subs, false, keywords, null, offset, limit,
ReadingOrder.desc, true);
for (FeedEntryStatus status : entriesStatus) {
list.add(Entry.build(status, applicationSettingsService.get()
.getPublicUrl(), applicationSettingsService.get()
list.add(Entry.build(status, applicationSettingsService.get().getPublicUrl(), applicationSettingsService.get()
.isImageProxyEnabled()));
}

View File

@@ -124,13 +124,15 @@ public class FeedREST extends AbstractResourceREST {
@Path("/entries")
@GET
@ApiOperation(value = "Get feed entries", notes = "Get a list of feed entries", responseClass = "com.commafeed.frontend.model.Entries")
public Response getFeedEntries(
@ApiParam(value = "id of the feed", required = true) @QueryParam("id") String id,
@ApiParam(value = "all entries or only unread ones", allowableValues = "all,unread", required = true) @DefaultValue("unread") @QueryParam("readType") ReadType readType,
@ApiParam(value = "only entries newer than this") @QueryParam("newerThan") Long newerThan,
@ApiParam(value = "offset for paging") @DefaultValue("0") @QueryParam("offset") int offset,
@ApiParam(value = "limit for paging, default 20, maximum 50") @DefaultValue("20") @QueryParam("limit") int limit,
@ApiParam(value = "date ordering", allowableValues = "asc,desc") @QueryParam("order") @DefaultValue("desc") ReadingOrder order) {
public Response getFeedEntries(@ApiParam(value = "id of the feed", required = true) @QueryParam("id") String id, @ApiParam(
value = "all entries or only unread ones",
allowableValues = "all,unread",
required = true) @DefaultValue("unread") @QueryParam("readType") ReadType readType, @ApiParam(
value = "only entries newer than this") @QueryParam("newerThan") Long newerThan,
@ApiParam(value = "offset for paging") @DefaultValue("0") @QueryParam("offset") int offset, @ApiParam(
value = "limit for paging, default 20, maximum 50") @DefaultValue("20") @QueryParam("limit") int limit, @ApiParam(
value = "date ordering",
allowableValues = "asc,desc") @QueryParam("order") @DefaultValue("desc") ReadingOrder order) {
Preconditions.checkNotNull(id);
Preconditions.checkNotNull(readType);
@@ -141,27 +143,22 @@ public class FeedREST extends AbstractResourceREST {
Entries entries = new Entries();
boolean unreadOnly = readType == ReadType.unread;
Date newerThanDate = newerThan == null ? null : new Date(
Long.valueOf(newerThan));
Date newerThanDate = newerThan == null ? null : new Date(Long.valueOf(newerThan));
FeedSubscription subscription = feedSubscriptionDAO.findById(getUser(),
Long.valueOf(id));
FeedSubscription subscription = feedSubscriptionDAO.findById(getUser(), Long.valueOf(id));
if (subscription != null) {
entries.setName(subscription.getTitle());
entries.setMessage(subscription.getFeed().getMessage());
entries.setErrorCount(subscription.getFeed().getErrorCount());
entries.setFeedLink(subscription.getFeed().getLink());
List<FeedEntryStatus> list = feedEntryStatusDAO
.findBySubscriptions(Arrays.asList(subscription),
unreadOnly, null, newerThanDate, offset, limit + 1,
order, true);
List<FeedEntryStatus> list = feedEntryStatusDAO.findBySubscriptions(Arrays.asList(subscription), unreadOnly, null,
newerThanDate, offset, limit + 1, order, true);
for (FeedEntryStatus status : list) {
entries.getEntries().add(
Entry.build(status, applicationSettingsService.get()
.getPublicUrl(), applicationSettingsService
.get().isImageProxyEnabled()));
Entry.build(status, applicationSettingsService.get().getPublicUrl(), applicationSettingsService.get()
.isImageProxyEnabled()));
}
boolean hasMore = entries.getEntries().size() > limit;
@@ -180,8 +177,7 @@ public class FeedREST extends AbstractResourceREST {
@ApiOperation(value = "Get feed entries as a feed", notes = "Get a feed of feed entries")
@Produces(MediaType.APPLICATION_XML)
@SecurityCheck(value = Role.USER, apiKeyAllowed = true)
public Response getFeedEntriesAsFeed(
@ApiParam(value = "id of the feed", required = true) @QueryParam("id") String id) {
public Response getFeedEntriesAsFeed(@ApiParam(value = "id of the feed", required = true) @QueryParam("id") String id) {
Preconditions.checkNotNull(id);
@@ -190,8 +186,7 @@ public class FeedREST extends AbstractResourceREST {
int offset = 0;
int limit = 20;
Entries entries = (Entries) getFeedEntries(id, readType, null, offset,
limit, order).getEntity();
Entries entries = (Entries) getFeedEntries(id, readType, null, offset, limit, order).getEntity();
SyndFeed feed = new SyndFeedImpl();
feed.setFeedType("rss_2.0");
@@ -222,16 +217,13 @@ public class FeedREST extends AbstractResourceREST {
url = StringUtils.trimToEmpty(url);
url = prependHttp(url);
try {
FetchedFeed feed = feedFetcher.fetch(url, true, null, null, null,
null);
FetchedFeed feed = feedFetcher.fetch(url, true, null, null, null, null);
info = new FeedInfo();
info.setUrl(feed.getFeed().getUrl());
info.setTitle(feed.getTitle());
} catch (Exception e) {
throw new WebApplicationException(e, Response
.status(Status.INTERNAL_SERVER_ERROR)
.entity(e.getMessage()).build());
throw new WebApplicationException(e, Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build());
}
return info;
}
@@ -239,8 +231,7 @@ public class FeedREST extends AbstractResourceREST {
@POST
@Path("/fetch")
@ApiOperation(value = "Fetch a feed", notes = "Fetch a feed by its url", responseClass = "com.commafeed.frontend.model.FeedInfo")
public Response fetchFeed(
@ApiParam(value = "feed url", required = true) FeedInfoRequest req) {
public Response fetchFeed(@ApiParam(value = "feed url", required = true) FeedInfoRequest req) {
Preconditions.checkNotNull(req);
Preconditions.checkNotNull(req.getUrl());
@@ -248,8 +239,7 @@ public class FeedREST extends AbstractResourceREST {
try {
info = fetchFeedInternal(req.getUrl());
} catch (Exception e) {
return Response.status(Status.INTERNAL_SERVER_ERROR)
.entity(e.getMessage()).build();
return Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
return Response.ok(info).build();
}
@@ -262,8 +252,7 @@ public class FeedREST extends AbstractResourceREST {
Preconditions.checkNotNull(req);
Preconditions.checkNotNull(req.getId());
FeedSubscription sub = feedSubscriptionDAO.findById(getUser(),
req.getId());
FeedSubscription sub = feedSubscriptionDAO.findById(getUser(), req.getId());
if (sub != null) {
Feed feed = sub.getFeed();
feed.setUrgent(true);
@@ -277,19 +266,15 @@ public class FeedREST extends AbstractResourceREST {
@Path("/mark")
@POST
@ApiOperation(value = "Mark feed entries", notes = "Mark feed entries as read (unread is not supported)")
public Response markFeedEntries(
@ApiParam(value = "Mark request") MarkRequest req) {
public Response markFeedEntries(@ApiParam(value = "Mark request") MarkRequest req) {
Preconditions.checkNotNull(req);
Preconditions.checkNotNull(req.getId());
Date olderThan = req.getOlderThan() == null ? null : new Date(
req.getOlderThan());
Date olderThan = req.getOlderThan() == null ? null : new Date(req.getOlderThan());
FeedSubscription subscription = feedSubscriptionDAO.findById(getUser(),
Long.valueOf(req.getId()));
FeedSubscription subscription = feedSubscriptionDAO.findById(getUser(), Long.valueOf(req.getId()));
if (subscription != null) {
feedEntryStatusDAO.markSubscriptionEntries(
Arrays.asList(subscription), olderThan);
feedEntryStatusDAO.markSubscriptionEntries(Arrays.asList(subscription), olderThan);
}
cache.invalidateUserData(getUser());
return Response.ok(Status.OK).build();
@@ -298,33 +283,27 @@ public class FeedREST extends AbstractResourceREST {
@GET
@Path("/get/{id}")
@ApiOperation(value = "", notes = "")
public Response get(
@ApiParam(value = "user id", required = true) @PathParam("id") Long id) {
public Response get(@ApiParam(value = "user id", required = true) @PathParam("id") Long id) {
Preconditions.checkNotNull(id);
FeedSubscription sub = feedSubscriptionDAO.findById(getUser(), id);
if (sub == null) {
return Response.status(Status.NOT_FOUND).build();
}
Long unreadCount = feedSubscriptionService.getUnreadCount(getUser())
.get(id);
Long unreadCount = feedSubscriptionService.getUnreadCount(getUser()).get(id);
if (unreadCount == null) {
unreadCount = new Long(0);
}
return Response.ok(
Subscription.build(sub, applicationSettingsService.get()
.getPublicUrl(), unreadCount)).build();
return Response.ok(Subscription.build(sub, applicationSettingsService.get().getPublicUrl(), unreadCount)).build();
}
@GET
@Path("/favicon/{id}")
@ApiOperation(value = "Fetch a feed's icon", notes = "Fetch a feed's icon")
public Response getFavicon(
@ApiParam(value = "subscription id") @PathParam("id") Long id) {
public Response getFavicon(@ApiParam(value = "subscription id") @PathParam("id") Long id) {
Preconditions.checkNotNull(id);
FeedSubscription subscription = feedSubscriptionDAO.findById(getUser(),
id);
FeedSubscription subscription = feedSubscriptionDAO.findById(getUser(), id);
if (subscription == null) {
return Response.status(Status.NOT_FOUND).build();
}
@@ -334,11 +313,8 @@ public class FeedREST extends AbstractResourceREST {
ResponseBuilder builder = null;
if (icon == null) {
String baseUrl = FeedUtils
.removeTrailingSlash(applicationSettingsService.get()
.getPublicUrl());
builder = Response.status(Status.MOVED_PERMANENTLY).location(
URI.create(baseUrl + "/images/default_favicon.gif"));
String baseUrl = FeedUtils.removeTrailingSlash(applicationSettingsService.get().getPublicUrl());
builder = Response.status(Status.MOVED_PERMANENTLY).location(URI.create(baseUrl + "/images/default_favicon.gif"));
} else {
builder = Response.ok(icon, "image/x-icon");
}
@@ -360,8 +336,7 @@ public class FeedREST extends AbstractResourceREST {
@POST
@Path("/subscribe")
@ApiOperation(value = "Subscribe to a feed", notes = "Subscribe to a feed")
public Response subscribe(
@ApiParam(value = "subscription request", required = true) SubscribeRequest req) {
public Response subscribe(@ApiParam(value = "subscription request", required = true) SubscribeRequest req) {
Preconditions.checkNotNull(req);
Preconditions.checkNotNull(req.getTitle());
Preconditions.checkNotNull(req.getUrl());
@@ -370,18 +345,13 @@ public class FeedREST extends AbstractResourceREST {
try {
url = fetchFeedInternal(url).getUrl();
FeedCategory category = CategoryREST.ALL
.equals(req.getCategoryId()) ? null : feedCategoryDAO
.findById(Long.valueOf(req.getCategoryId()));
FeedCategory category = CategoryREST.ALL.equals(req.getCategoryId()) ? null : feedCategoryDAO.findById(Long.valueOf(req
.getCategoryId()));
FeedInfo info = fetchFeedInternal(url);
feedSubscriptionService.subscribe(getUser(), info.getUrl(),
req.getTitle(), category);
feedSubscriptionService.subscribe(getUser(), info.getUrl(), req.getTitle(), category);
} catch (Exception e) {
log.info("Failed to subscribe to URL {}: {}", url, e.getMessage());
return Response
.status(Status.SERVICE_UNAVAILABLE)
.entity("Failed to subscribe to URL " + url + ": "
+ e.getMessage()).build();
return Response.status(Status.SERVICE_UNAVAILABLE).entity("Failed to subscribe to URL " + url + ": " + e.getMessage()).build();
}
cache.invalidateUserData(getUser());
return Response.ok(Status.OK).build();
@@ -390,8 +360,7 @@ public class FeedREST extends AbstractResourceREST {
@GET
@Path("/subscribe")
@ApiOperation(value = "Subscribe to a feed", notes = "Subscribe to a feed")
public Response subscribe(
@ApiParam(value = "feed url", required = true) @QueryParam("url") String url) {
public Response subscribe(@ApiParam(value = "feed url", required = true) @QueryParam("url") String url) {
try {
Preconditions.checkNotNull(url);
@@ -400,14 +369,11 @@ public class FeedREST extends AbstractResourceREST {
url = fetchFeedInternal(url).getUrl();
FeedInfo info = fetchFeedInternal(url);
feedSubscriptionService.subscribe(getUser(), info.getUrl(),
info.getTitle(), null);
feedSubscriptionService.subscribe(getUser(), info.getUrl(), info.getTitle(), null);
} catch (Exception e) {
log.info("Could not subscribe to url {} : {}", url, e.getMessage());
}
return Response.temporaryRedirect(
URI.create(applicationSettingsService.get().getPublicUrl()))
.build();
return Response.temporaryRedirect(URI.create(applicationSettingsService.get().getPublicUrl())).build();
}
private String prependHttp(String url) {
@@ -424,8 +390,7 @@ public class FeedREST extends AbstractResourceREST {
Preconditions.checkNotNull(req);
Preconditions.checkNotNull(req.getId());
FeedSubscription sub = feedSubscriptionDAO.findById(getUser(),
req.getId());
FeedSubscription sub = feedSubscriptionDAO.findById(getUser(), req.getId());
if (sub != null) {
feedSubscriptionDAO.delete(sub);
cache.invalidateUserData(getUser());
@@ -438,41 +403,34 @@ public class FeedREST extends AbstractResourceREST {
@POST
@Path("/modify")
@ApiOperation(value = "Modify a subscription", notes = "Modify a feed subscription")
public Response modify(
@ApiParam(value = "subscription id", required = true) FeedModificationRequest req) {
public Response modify(@ApiParam(value = "subscription id", required = true) FeedModificationRequest req) {
Preconditions.checkNotNull(req);
Preconditions.checkNotNull(req.getId());
FeedSubscription subscription = feedSubscriptionDAO.findById(getUser(),
req.getId());
FeedSubscription subscription = feedSubscriptionDAO.findById(getUser(), req.getId());
if (StringUtils.isNotBlank(req.getName())) {
subscription.setTitle(req.getName());
}
FeedCategory parent = null;
if (req.getCategoryId() != null
&& !CategoryREST.ALL.equals(req.getCategoryId())) {
parent = feedCategoryDAO.findById(getUser(),
Long.valueOf(req.getCategoryId()));
if (req.getCategoryId() != null && !CategoryREST.ALL.equals(req.getCategoryId())) {
parent = feedCategoryDAO.findById(getUser(), Long.valueOf(req.getCategoryId()));
}
subscription.setCategory(parent);
if (req.getPosition() != null) {
List<FeedSubscription> subs = feedSubscriptionDAO.findByCategory(
getUser(), parent);
List<FeedSubscription> subs = feedSubscriptionDAO.findByCategory(getUser(), parent);
Collections.sort(subs, new Comparator<FeedSubscription>() {
@Override
public int compare(FeedSubscription o1, FeedSubscription o2) {
return ObjectUtils.compare(o1.getPosition(),
o2.getPosition());
return ObjectUtils.compare(o1.getPosition(), o2.getPosition());
}
});
int existingIndex = -1;
for (int i = 0; i < subs.size(); i++) {
if (ObjectUtils.equals(subs.get(i).getId(),
subscription.getId())) {
if (ObjectUtils.equals(subs.get(i).getId(), subscription.getId())) {
existingIndex = i;
}
}
@@ -500,22 +458,19 @@ public class FeedREST extends AbstractResourceREST {
String publicUrl = applicationSettingsService.get().getPublicUrl();
if (StringUtils.isBlank(publicUrl)) {
throw new WebApplicationException(Response
.status(Status.INTERNAL_SERVER_ERROR)
throw new WebApplicationException(Response.status(Status.INTERNAL_SERVER_ERROR)
.entity("Set the public URL in the admin section.").build());
}
if (StartupBean.USERNAME_DEMO.equals(getUser().getName())) {
return Response.status(Status.FORBIDDEN)
.entity("Import is disabled for the demo account").build();
return Response.status(Status.FORBIDDEN).entity("Import is disabled for the demo account").build();
}
try {
FileItemFactory factory = new DiskFileItemFactory(1000000, null);
ServletFileUpload upload = new ServletFileUpload(factory);
for (FileItem item : upload.parseRequest(request)) {
if ("file".equals(item.getFieldName())) {
String opml = IOUtils.toString(item.getInputStream(),
"UTF-8");
String opml = IOUtils.toString(item.getInputStream(), "UTF-8");
if (StringUtils.isNotBlank(opml)) {
opmlImporter.importOpml(getUser(), opml);
}
@@ -523,14 +478,10 @@ public class FeedREST extends AbstractResourceREST {
}
}
} catch (Exception e) {
throw new WebApplicationException(Response
.status(Status.INTERNAL_SERVER_ERROR)
.entity(e.getMessage()).build());
throw new WebApplicationException(Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build());
}
cache.invalidateUserData(getUser());
return Response.temporaryRedirect(
URI.create(applicationSettingsService.get().getPublicUrl()))
.build();
return Response.temporaryRedirect(URI.create(applicationSettingsService.get().getPublicUrl())).build();
}
@GET
@@ -544,8 +495,7 @@ public class FeedREST extends AbstractResourceREST {
try {
opmlString = output.outputString(opml);
} catch (Exception e) {
return Response.status(Status.INTERNAL_SERVER_ERROR).entity(e)
.build();
return Response.status(Status.INTERNAL_SERVER_ERROR).entity(e).build();
}
return Response.ok(opmlString).build();
}

View File

@@ -33,8 +33,7 @@ import com.google.api.client.repackaged.com.google.common.base.Preconditions;
@Path("/push")
public class PubSubHubbubCallbackREST {
private static Logger log = LoggerFactory
.getLogger(PubSubHubbubCallbackREST.class);
private static Logger log = LoggerFactory.getLogger(PubSubHubbubCallbackREST.class);
@Context
HttpServletRequest request;
@@ -57,13 +56,10 @@ public class PubSubHubbubCallbackREST {
@Path("/callback")
@GET
@Produces(MediaType.TEXT_PLAIN)
public Response verify(@QueryParam("hub.mode") String mode,
@QueryParam("hub.topic") String topic,
@QueryParam("hub.challenge") String challenge,
@QueryParam("hub.lease_seconds") String leaseSeconds,
public Response verify(@QueryParam("hub.mode") String mode, @QueryParam("hub.topic") String topic,
@QueryParam("hub.challenge") String challenge, @QueryParam("hub.lease_seconds") String leaseSeconds,
@QueryParam("hub.verify_token") String verifyToken) {
if (!applicationSettingsService.get()
.isPubsubhubbub()) {
if (!applicationSettingsService.get().isPubsubhubbub()) {
return Response.status(Status.FORBIDDEN).entity("pubsubhubbub is disabled").build();
}
@@ -76,8 +72,7 @@ public class PubSubHubbubCallbackREST {
if (feeds.isEmpty() == false) {
for (Feed feed : feeds) {
log.debug("activated push notifications for {}",
feed.getPushTopic());
log.debug("activated push notifications for {}", feed.getPushTopic());
feed.setPushLastPing(new Date());
}
feedDAO.saveOrUpdate(feeds);
@@ -92,8 +87,7 @@ public class PubSubHubbubCallbackREST {
@POST
@Consumes({ MediaType.APPLICATION_ATOM_XML, "application/rss+xml" })
public Response callback() {
if (!applicationSettingsService.get()
.isPubsubhubbub()) {
if (!applicationSettingsService.get().isPubsubhubbub()) {
return Response.status(Status.FORBIDDEN).entity("pubsubhubbub is disabled").build();
}
try {

View File

@@ -34,10 +34,8 @@ public class ServerREST extends AbstractResourceREST {
ApplicationPropertiesService properties = ApplicationPropertiesService.get();
ServerInfo infos = new ServerInfo();
infos.setAnnouncement(applicationSettingsService.get()
.getAnnouncement());
infos.getSupportedLanguages().putAll(
startupBean.getSupportedLanguages());
infos.setAnnouncement(applicationSettingsService.get().getAnnouncement());
infos.getSupportedLanguages().putAll(startupBean.getSupportedLanguages());
infos.setVersion(properties.getVersion());
infos.setGitCommit(properties.getGitCommit());
return Response.ok(infos).build();
@@ -57,8 +55,7 @@ public class ServerREST extends AbstractResourceREST {
HttpResult result = httpGetter.getBinary(url, 20000);
return Response.ok(result.getContent()).build();
} catch (Exception e) {
return Response.status(Status.SERVICE_UNAVAILABLE)
.entity(e.getMessage()).build();
return Response.status(Status.SERVICE_UNAVAILABLE).entity(e.getMessage()).build();
}
}
}

View File

@@ -66,7 +66,10 @@ public class UserREST extends AbstractResourceREST {
@Path("/settings")
@GET
@ApiOperation(value = "Retrieve user settings", notes = "Retrieve user settings", responseClass = "com.commafeed.frontend.model.Settings")
@ApiOperation(
value = "Retrieve user settings",
notes = "Retrieve user settings",
responseClass = "com.commafeed.frontend.model.Settings")
public Response getSettings() {
Settings s = new Settings();
UserSettings settings = userSettingsDAO.findByUser(getUser());
@@ -149,16 +152,13 @@ public class UserREST extends AbstractResourceREST {
@Path("/profile")
@POST
@ApiOperation(value = "Save user's profile")
public Response save(
@ApiParam(required = true) ProfileModificationRequest request) {
public Response save(@ApiParam(required = true) ProfileModificationRequest request) {
User user = getUser();
Preconditions.checkArgument(StringUtils.isBlank(request.getPassword())
|| request.getPassword().length() >= 6);
Preconditions.checkArgument(StringUtils.isBlank(request.getPassword()) || request.getPassword().length() >= 6);
if (StringUtils.isNotBlank(request.getEmail())) {
User u = userDAO.findByEmail(request.getEmail());
Preconditions.checkArgument(u == null
|| user.getId().equals(u.getId()));
Preconditions.checkArgument(u == null || user.getId().equals(u.getId()));
}
if (StartupBean.USERNAME_DEMO.equals(user.getName())) {
@@ -167,8 +167,7 @@ public class UserREST extends AbstractResourceREST {
user.setEmail(StringUtils.trimToNull(request.getEmail()));
if (StringUtils.isNotBlank(request.getPassword())) {
byte[] password = encryptionService.getEncryptedPassword(
request.getPassword(), user.getSalt());
byte[] password = encryptionService.getEncryptedPassword(request.getPassword(), user.getSalt());
user.setPassword(password);
user.setApiKey(userService.generateApiKey(user));
}
@@ -185,12 +184,10 @@ public class UserREST extends AbstractResourceREST {
@SecurityCheck(Role.NONE)
public Response register(@ApiParam(required = true) RegistrationRequest req) {
try {
userService.register(req.getName(), req.getPassword(),
req.getEmail(), Arrays.asList(Role.USER));
userService.register(req.getName(), req.getPassword(), req.getEmail(), Arrays.asList(Role.USER));
return Response.ok().build();
} catch (Exception e) {
return Response.status(Status.INTERNAL_SERVER_ERROR)
.entity(e.getMessage()).build();
return Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
@@ -199,8 +196,7 @@ public class UserREST extends AbstractResourceREST {
@POST
@ApiOperation(value = "Delete the user account")
public Response delete() {
if (StartupBean.USERNAME_ADMIN.equals(getUser().getName())
|| StartupBean.USERNAME_DEMO.equals(getUser().getName())) {
if (StartupBean.USERNAME_ADMIN.equals(getUser().getName()) || StartupBean.USERNAME_DEMO.equals(getUser().getName())) {
return Response.status(Status.FORBIDDEN).build();
}
userService.unregister(getUser());