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

@@ -49,15 +49,12 @@ import com.commafeed.frontend.utils.exception.DisplayExceptionPage;
public class CommaFeedApplication extends AuthenticatedWebApplication {
private static Logger log = LoggerFactory
.getLogger(CommaFeedApplication.class);
private static Logger log = LoggerFactory.getLogger(CommaFeedApplication.class);
public CommaFeedApplication() {
super();
String prod = ResourceBundle.getBundle("application").getString(
"production");
setConfigurationType(Boolean.valueOf(prod) ? RuntimeConfigurationType.DEPLOYMENT
: RuntimeConfigurationType.DEVELOPMENT);
String prod = ResourceBundle.getBundle("application").getString("production");
setConfigurationType(Boolean.valueOf(prod) ? RuntimeConfigurationType.DEPLOYMENT : RuntimeConfigurationType.DEVELOPMENT);
}
@Override
@@ -66,16 +63,16 @@ public class CommaFeedApplication extends AuthenticatedWebApplication {
mountPage("welcome", WelcomePage.class);
mountPage("demo", DemoLoginPage.class);
mountPage("recover", PasswordRecoveryPage.class);
mountPage("recover2", PasswordRecoveryCallbackPage.class);
mountPage("logout", LogoutPage.class);
mountPage("error", DisplayExceptionPage.class);
// mountPage("google/import/redirect", GoogleImportRedirectPage.class);
// mountPage(GoogleImportCallbackPage.PAGE_PATH,
// GoogleImportCallbackPage.class);
// mountPage("google/import/redirect", GoogleImportRedirectPage.class);
// mountPage(GoogleImportCallbackPage.PAGE_PATH,
// GoogleImportCallbackPage.class);
mountPage("next", NextUnreadRedirectPage.class);
@@ -89,8 +86,7 @@ public class CommaFeedApplication extends AuthenticatedWebApplication {
setHeaderResponseDecorator(new IHeaderResponseDecorator() {
@Override
public IHeaderResponse decorate(IHeaderResponse response) {
return new JavaScriptFilteredIntoFooterHeaderResponse(response,
"footer-container");
return new JavaScriptFilteredIntoFooterHeaderResponse(response, "footer-container");
}
});
@@ -100,61 +96,52 @@ public class CommaFeedApplication extends AuthenticatedWebApplication {
AjaxRequestTarget target = cycle.find(AjaxRequestTarget.class);
// redirect to the error page if ajax request, render error on
// current page otherwise
RedirectPolicy policy = target == null ? RedirectPolicy.NEVER_REDIRECT
: RedirectPolicy.AUTO_REDIRECT;
return new RenderPageRequestHandler(new PageProvider(
new DisplayExceptionPage(ex)), policy);
RedirectPolicy policy = target == null ? RedirectPolicy.NEVER_REDIRECT : RedirectPolicy.AUTO_REDIRECT;
return new RenderPageRequestHandler(new PageProvider(new DisplayExceptionPage(ex)), policy);
}
});
}
private void setupSecurity() {
getSecuritySettings().setAuthenticationStrategy(
new DefaultAuthenticationStrategy("LoggedIn") {
getSecuritySettings().setAuthenticationStrategy(new DefaultAuthenticationStrategy("LoggedIn") {
private CookieUtils cookieUtils = null;
private CookieUtils cookieUtils = null;
@Override
protected CookieUtils getCookieUtils() {
@Override
protected CookieUtils getCookieUtils() {
if (cookieUtils == null) {
cookieUtils = new CookieUtils() {
@Override
protected void initializeCookie(Cookie cookie) {
super.initializeCookie(cookie);
cookie.setHttpOnly(true);
}
};
if (cookieUtils == null) {
cookieUtils = new CookieUtils() {
@Override
protected void initializeCookie(Cookie cookie) {
super.initializeCookie(cookie);
cookie.setHttpOnly(true);
}
return cookieUtils;
}
});
getSecuritySettings().setAuthorizationStrategy(
new IAuthorizationStrategy() {
};
}
return cookieUtils;
}
});
getSecuritySettings().setAuthorizationStrategy(new IAuthorizationStrategy() {
@Override
public <T extends IRequestableComponent> boolean isInstantiationAuthorized(
Class<T> componentClass) {
boolean authorized = true;
@Override
public <T extends IRequestableComponent> boolean isInstantiationAuthorized(Class<T> componentClass) {
boolean authorized = true;
boolean restricted = componentClass
.isAnnotationPresent(SecurityCheck.class);
if (restricted) {
SecurityCheck annotation = componentClass
.getAnnotation(SecurityCheck.class);
Roles roles = CommaFeedSession.get().getRoles();
authorized = roles.hasAnyRole(new Roles(annotation
.value().name()));
}
return authorized;
}
boolean restricted = componentClass.isAnnotationPresent(SecurityCheck.class);
if (restricted) {
SecurityCheck annotation = componentClass.getAnnotation(SecurityCheck.class);
Roles roles = CommaFeedSession.get().getRoles();
authorized = roles.hasAnyRole(new Roles(annotation.value().name()));
}
return authorized;
}
@Override
public boolean isActionAuthorized(Component component,
Action action) {
return true;
}
});
@Override
public boolean isActionAuthorized(Component component, Action action) {
return true;
}
});
}
@Override
@@ -164,10 +151,8 @@ public class CommaFeedApplication extends AuthenticatedWebApplication {
protected void setupInjection() {
try {
BeanManager beanManager = (BeanManager) new InitialContext()
.lookup("java:comp/BeanManager");
new CdiConfiguration(beanManager).setPropagation(
ConversationPropagation.NONE).configure(this);
BeanManager beanManager = (BeanManager) new InitialContext().lookup("java:comp/BeanManager");
new CdiConfiguration(beanManager).setPropagation(ConversationPropagation.NONE).configure(this);
} catch (NamingException e) {
log.warn("Could not locate bean manager. CDI is disabled.");
}

View File

@@ -24,8 +24,7 @@ import com.wordnik.swagger.annotations.ApiProperty;
@ApiClass("Entry details")
public class Entry implements Serializable {
public static Entry build(FeedEntryStatus status, String publicUrl,
boolean proxyImages) {
public static Entry build(FeedEntryStatus status, String publicUrl, boolean proxyImages) {
Entry entry = new Entry();
FeedEntry feedEntry = status.getEntry();
@@ -38,8 +37,7 @@ public class Entry implements Serializable {
entry.setId(String.valueOf(feedEntry.getId()));
entry.setGuid(feedEntry.getGuid());
entry.setTitle(feedEntry.getContent().getTitle());
entry.setContent(FeedUtils.proxyImages(feedEntry.getContent()
.getContent(), publicUrl, proxyImages));
entry.setContent(FeedUtils.proxyImages(feedEntry.getContent().getContent(), publicUrl, proxyImages));
entry.setRtl(FeedUtils.isRTL(feedEntry));
entry.setAuthor(feedEntry.getContent().getAuthor());
entry.setEnclosureUrl(feedEntry.getContent().getEnclosureUrl());

View File

@@ -20,8 +20,7 @@ import com.wordnik.swagger.annotations.ApiProperty;
@ApiClass("User information")
public class Subscription implements Serializable {
public static Subscription build(FeedSubscription subscription,
String publicUrl, long unreadCount) {
public static Subscription build(FeedSubscription subscription, String publicUrl, long unreadCount) {
Date now = new Date();
FeedCategory category = subscription.getCategory();
Feed feed = subscription.getFeed();
@@ -35,12 +34,9 @@ public class Subscription implements Serializable {
sub.setFeedLink(feed.getLink());
sub.setIconUrl(FeedUtils.getFaviconUrl(subscription, publicUrl));
sub.setLastRefresh(feed.getLastUpdated());
sub.setNextRefresh((feed.getDisabledUntil() != null && feed
.getDisabledUntil().before(now)) ? null : feed
.getDisabledUntil());
sub.setNextRefresh((feed.getDisabledUntil() != null && feed.getDisabledUntil().before(now)) ? null : feed.getDisabledUntil());
sub.setUnread(unreadCount);
sub.setCategoryId(category == null ? null : String.valueOf(category
.getId()));
sub.setCategoryId(category == null ? null : String.valueOf(category.getId()));
return sub;
}

View File

@@ -14,7 +14,7 @@ import com.wordnik.swagger.annotations.ApiProperty;
@XmlAccessorType(XmlAccessType.FIELD)
@ApiClass("Feed information request")
public class FeedInfoRequest implements Serializable {
@ApiProperty(value = "feed url", required = true)
private String url;
@@ -25,7 +25,5 @@ public class FeedInfoRequest implements Serializable {
public void setUrl(String url) {
this.url = url;
}
}

View File

@@ -24,7 +24,9 @@ public class MarkRequest implements Serializable {
@ApiProperty(value = "mark as read or unread")
private boolean read;
@ApiProperty(value = "only entries older than this, pass the timestamp you got from the entry list to prevent marking an entry that was not retrieved", required = false)
@ApiProperty(
value = "only entries older than this, pass the timestamp you got from the entry list to prevent marking an entry that was not retrieved",
required = false)
private Long olderThan;
public String getId() {

View File

@@ -79,15 +79,12 @@ public abstract class BasePage extends WebPage {
if (user != null) {
UserSettings settings = userSettingsDAO.findByUser(user);
if (settings != null) {
lang = settings.getLanguage() == null ? "en" : settings
.getLanguage();
theme = settings.getTheme() == null ? "default" : settings
.getTheme();
lang = settings.getLanguage() == null ? "en" : settings.getLanguage();
theme = settings.getTheme() == null ? "default" : settings.getTheme();
}
}
add(new TransparentWebMarkupContainer("html").setMarkupId(
"theme-" + theme).add(new AttributeModifier("lang", lang)));
add(new TransparentWebMarkupContainer("html").setMarkupId("theme-" + theme).add(new AttributeModifier("lang", lang)));
settings = applicationSettingsService.get();
add(new HeaderResponseContainer("footer-container", "footer-container"));
@@ -107,8 +104,7 @@ public abstract class BasePage extends WebPage {
if (getApplication().getConfigurationType() == RuntimeConfigurationType.DEPLOYMENT) {
long startupTime = startupBean.getStartupTime();
String suffix = "?" + startupTime;
response.render(JavaScriptHeaderItem.forUrl("static/all.js"
+ suffix));
response.render(JavaScriptHeaderItem.forUrl("static/all.js" + suffix));
response.render(CssHeaderItem.forUrl("static/all.css" + suffix));
} else {
response.render(JavaScriptHeaderItem.forUrl("wro/lib.js"));

View File

@@ -16,8 +16,7 @@ public class DemoLoginPage extends WebPage {
UserService userService;
public DemoLoginPage() {
CommaFeedSession.get().authenticate(StartupBean.USERNAME_DEMO,
StartupBean.USERNAME_DEMO);
CommaFeedSession.get().authenticate(StartupBean.USERNAME_DEMO, StartupBean.USERNAME_DEMO);
setResponsePage(getApplication().getHomePage());
}
}

View File

@@ -55,8 +55,7 @@ public class GoogleImportCallbackPage extends WebPage {
if (request.getQueryString() != null) {
urlBuffer.append('?').append(request.getQueryString());
}
AuthorizationCodeResponseUrl responseUrl = new AuthorizationCodeResponseUrl(
urlBuffer.toString());
AuthorizationCodeResponseUrl responseUrl = new AuthorizationCodeResponseUrl(urlBuffer.toString());
String code = responseUrl.getCode();
if (responseUrl.getError() != null) {
@@ -73,8 +72,8 @@ public class GoogleImportCallbackPage extends WebPage {
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
AuthorizationCodeTokenRequest tokenRequest = new AuthorizationCodeTokenRequest(
httpTransport, jsonFactory, new GenericUrl(TOKEN_URL), code);
AuthorizationCodeTokenRequest tokenRequest = new AuthorizationCodeTokenRequest(httpTransport, jsonFactory, new GenericUrl(
TOKEN_URL), code);
tokenRequest.setRedirectUri(redirectUri);
tokenRequest.put("client_id", clientId);
tokenRequest.put("client_secret", clientSecret);
@@ -87,16 +86,13 @@ public class GoogleImportCallbackPage extends WebPage {
TokenResponse tokenResponse = tokenRequest.execute();
String accessToken = tokenResponse.getAccessToken();
HttpRequest httpRequest = httpTransport.createRequestFactory()
.buildGetRequest(new GenericUrl(EXPORT_URL));
BearerToken.authorizationHeaderAccessMethod().intercept(
httpRequest, accessToken);
HttpRequest httpRequest = httpTransport.createRequestFactory().buildGetRequest(new GenericUrl(EXPORT_URL));
BearerToken.authorizationHeaderAccessMethod().intercept(httpRequest, accessToken);
String opml = httpRequest.execute().parseAsString();
User user = CommaFeedSession.get().getUser();
if (user != null) {
if (StartupBean.USERNAME_DEMO.equals(user.getName())) {
throw new DisplayException(
"Import is disabled for the demo account");
throw new DisplayException("Import is disabled for the demo account");
}
importer.importOpml(CommaFeedSession.get().getUser(), opml);
}

View File

@@ -15,8 +15,7 @@ import com.commafeed.backend.services.ApplicationSettingsService;
@SuppressWarnings("serial")
public class GoogleImportRedirectPage extends WebPage {
private static Logger log = Logger
.getLogger(GoogleImportRedirectPage.class);
private static Logger log = Logger.getLogger(GoogleImportRedirectPage.class);
private static final String SCOPE = "https://www.google.com/reader/subscriptions/export email profile";
private static final String AUTH_URL = "https://accounts.google.com/o/oauth2/auth";

View File

@@ -18,16 +18,12 @@ public class HomePage extends BasePage {
public void renderHead(IHeaderResponse response) {
super.renderHead(response);
response.render(CssHeaderItem.forReference(
new UserCustomCssReference() {
@Override
protected String getCss() {
UserSettings settings = userSettingsDAO
.findByUser(CommaFeedSession.get().getUser());
return settings == null ? null : settings
.getCustomCss();
}
}, new PageParameters().add("_t", System.currentTimeMillis()),
null));
response.render(CssHeaderItem.forReference(new UserCustomCssReference() {
@Override
protected String getCss() {
UserSettings settings = userSettingsDAO.findByUser(CommaFeedSession.get().getUser());
return settings == null ? null : settings.getCustomCss();
}
}, new PageParameters().add("_t", System.currentTimeMillis()), null));
}
}

View File

@@ -52,21 +52,15 @@ public class NextUnreadRedirectPage extends WebPage {
}
List<FeedEntryStatus> statuses = null;
if (StringUtils.isBlank(categoryId)
|| CategoryREST.ALL.equals(categoryId)) {
if (StringUtils.isBlank(categoryId) || CategoryREST.ALL.equals(categoryId)) {
List<FeedSubscription> subs = feedSubscriptionDAO.findAll(user);
statuses = feedEntryStatusDAO.findBySubscriptions(subs, true, null,
null, 0, 1, order, true);
statuses = feedEntryStatusDAO.findBySubscriptions(subs, true, null, null, 0, 1, order, true);
} else {
FeedCategory category = feedCategoryDAO.findById(user,
Long.valueOf(categoryId));
FeedCategory category = feedCategoryDAO.findById(user, Long.valueOf(categoryId));
if (category != null) {
List<FeedCategory> children = feedCategoryDAO
.findAllChildrenCategories(user, category);
List<FeedSubscription> subscriptions = feedSubscriptionDAO
.findByCategories(user, children);
statuses = feedEntryStatusDAO.findBySubscriptions(
subscriptions, true, null, null, 0, 1, order, true);
List<FeedCategory> children = feedCategoryDAO.findAllChildrenCategories(user, category);
List<FeedSubscription> subscriptions = feedSubscriptionDAO.findByCategories(user, children);
statuses = feedEntryStatusDAO.findBySubscriptions(subscriptions, true, null, null, 0, 1, order, true);
}
}

View File

@@ -40,12 +40,10 @@ public class PasswordRecoveryCallbackPage extends BasePage {
if (user == null) {
throw new DisplayException("email not found");
}
if (user.getRecoverPasswordToken() == null
|| !user.getRecoverPasswordToken().equals(token)) {
if (user.getRecoverPasswordToken() == null || !user.getRecoverPasswordToken().equals(token)) {
throw new DisplayException("invalid token");
}
if (user.getRecoverPasswordTokenDate().before(
DateUtils.addDays(new Date(), -2))) {
if (user.getRecoverPasswordTokenDate().before(DateUtils.addDays(new Date(), -2))) {
throw new DisplayException("token expired");
}
@@ -57,8 +55,7 @@ public class PasswordRecoveryCallbackPage extends BasePage {
protected void onSubmit() {
String passwd = password.getObject();
if (StringUtils.equals(passwd, confirm.getObject())) {
byte[] password = encryptionService.getEncryptedPassword(
passwd, user.getSalt());
byte[] password = encryptionService.getEncryptedPassword(passwd, user.getSalt());
user.setPassword(password);
user.setApiKey(userService.generateApiKey(user));
user.setRecoverPasswordToken(null);
@@ -71,10 +68,8 @@ public class PasswordRecoveryCallbackPage extends BasePage {
}
};
add(form);
form.add(new PasswordTextField("password", password).setResetPassword(
true).add(StringValidator.minimumLength(6)));
form.add(new PasswordTextField("confirm", confirm).setResetPassword(
true).add(StringValidator.minimumLength(6)));
form.add(new PasswordTextField("password", password).setResetPassword(true).add(StringValidator.minimumLength(6)));
form.add(new PasswordTextField("confirm", confirm).setResetPassword(true).add(StringValidator.minimumLength(6)));
form.add(new BookmarkablePageLink<Void>("cancel", HomePage.class));

View File

@@ -21,8 +21,7 @@ import com.commafeed.frontend.pages.components.BootstrapFeedbackPanel;
@SuppressWarnings("serial")
public class PasswordRecoveryPage extends BasePage {
private static Logger log = LoggerFactory
.getLogger(PasswordRecoveryPage.class);
private static Logger log = LoggerFactory.getLogger(PasswordRecoveryPage.class);
public PasswordRecoveryPage() {
@@ -37,12 +36,10 @@ public class PasswordRecoveryPage extends BasePage {
error("Email not found.");
} else {
try {
user.setRecoverPasswordToken(DigestUtils.sha1Hex(UUID
.randomUUID().toString()));
user.setRecoverPasswordToken(DigestUtils.sha1Hex(UUID.randomUUID().toString()));
user.setRecoverPasswordTokenDate(new Date());
userDAO.saveOrUpdate(user);
mailService.sendMail(user, "Password recovery",
buildEmailContent(user));
mailService.sendMail(user, "Password recovery", buildEmailContent(user));
info("Email sent.");
} catch (Exception e) {
log.error(e.getMessage(), e);
@@ -67,9 +64,7 @@ public class PasswordRecoveryPage extends BasePage {
private String buildEmailContent(User user) throws Exception {
String publicUrl = FeedUtils
.removeTrailingSlash(applicationSettingsService.get()
.getPublicUrl());
String publicUrl = FeedUtils.removeTrailingSlash(applicationSettingsService.get().getPublicUrl());
publicUrl += "/recover2";
return String
@@ -78,11 +73,7 @@ public class PasswordRecoveryPage extends BasePage {
}
private String callbackUrl(User user, String publicUrl) throws Exception {
return new URIBuilder(publicUrl)
.addParameter(PasswordRecoveryCallbackPage.PARAM_EMAIL,
user.getEmail())
.addParameter(PasswordRecoveryCallbackPage.PARAM_TOKEN,
user.getRecoverPasswordToken()).build().toURL()
.toString();
return new URIBuilder(publicUrl).addParameter(PasswordRecoveryCallbackPage.PARAM_EMAIL, user.getEmail())
.addParameter(PasswordRecoveryCallbackPage.PARAM_TOKEN, user.getRecoverPasswordToken()).build().toURL().toString();
}
}

View File

@@ -53,8 +53,7 @@ public class TestRssPage extends WebPage {
} catch (InterruptedException e) {
// do nothing
}
getRequestCycle().scheduleRequestHandlerAfterCurrent(
new TextRequestHandler("text/xml", "UTF-8", writer.toString()));
getRequestCycle().scheduleRequestHandlerAfterCurrent(new TextRequestHandler("text/xml", "UTF-8", writer.toString()));
}
}

View File

@@ -15,16 +15,14 @@ public class WelcomePage extends BasePage {
ApplicationSettingsService applicationSettingsService;
public WelcomePage() {
add(new BookmarkablePageLink<Void>("logo-link", getApplication()
.getHomePage()));
add(new BookmarkablePageLink<Void>("logo-link", getApplication().getHomePage()));
add(new BookmarkablePageLink<Void>("demo-login", DemoLoginPage.class));
add(new LoginPanel("login"));
add(new RegisterPanel("register") {
@Override
protected void onConfigure() {
super.onConfigure();
setVisibilityAllowed(applicationSettingsService.get()
.isAllowRegistrations());
setVisibilityAllowed(applicationSettingsService.get().isAllowRegistrations());
}
});
}

View File

@@ -19,11 +19,9 @@ public class LoginPanel extends SignInPanel {
public LoginPanel(String id) {
super(id);
replace(new BootstrapFeedbackPanel("feedback",
new ContainerFeedbackMessageFilter(this)));
replace(new BootstrapFeedbackPanel("feedback", new ContainerFeedbackMessageFilter(this)));
Form<?> form = (Form<?>) get("signInForm");
form.add(new BookmarkablePageLink<Void>("recover",
PasswordRecoveryPage.class){
form.add(new BookmarkablePageLink<Void>("recover", PasswordRecoveryPage.class) {
@Override
protected void onConfigure() {
super.onConfigure();

View File

@@ -45,62 +45,51 @@ public class RegisterPanel extends Panel {
IModel<RegistrationRequest> model = Model.of(new RegistrationRequest());
Form<RegistrationRequest> form = new StatelessForm<RegistrationRequest>(
"form", model) {
Form<RegistrationRequest> form = new StatelessForm<RegistrationRequest>("form", model) {
@Override
protected void onSubmit() {
if (applicationSettingsService.get().isAllowRegistrations()) {
RegistrationRequest req = getModelObject();
userService.register(req.getName(), req.getPassword(),
req.getEmail(), Arrays.asList(Role.USER));
userService.register(req.getName(), req.getPassword(), req.getEmail(), Arrays.asList(Role.USER));
IAuthenticationStrategy strategy = getApplication()
.getSecuritySettings().getAuthenticationStrategy();
IAuthenticationStrategy strategy = getApplication().getSecuritySettings().getAuthenticationStrategy();
strategy.save(req.getName(), req.getPassword());
CommaFeedSession.get().signIn(req.getName(),
req.getPassword());
CommaFeedSession.get().signIn(req.getName(), req.getPassword());
}
setResponsePage(getApplication().getHomePage());
}
};
add(form);
add(new BootstrapFeedbackPanel("feedback",
new ContainerFeedbackMessageFilter(form)));
add(new BootstrapFeedbackPanel("feedback", new ContainerFeedbackMessageFilter(form)));
RegistrationRequest p = MF.p(RegistrationRequest.class);
form.add(new RequiredTextField<String>("name", MF.m(model, p.getName()))
.add(StringValidator.lengthBetween(3, 32)).add(
new IValidator<String>() {
@Override
public void validate(
IValidatable<String> validatable) {
String name = validatable.getValue();
User user = userDAO.findByName(name);
if (user != null) {
validatable.error(new ValidationError(
"Name is already taken."));
}
}
}));
form.add(new PasswordTextField("password", MF.m(model, p.getPassword()))
.setResetPassword(false).add(StringValidator.minimumLength(6)));
form.add(new RequiredTextField<String>("email", MF.m(model,
p.getEmail())) {
form.add(new RequiredTextField<String>("name", MF.m(model, p.getName())).add(StringValidator.lengthBetween(3, 32)).add(
new IValidator<String>() {
@Override
public void validate(IValidatable<String> validatable) {
String name = validatable.getValue();
User user = userDAO.findByName(name);
if (user != null) {
validatable.error(new ValidationError("Name is already taken."));
}
}
}));
form.add(new PasswordTextField("password", MF.m(model, p.getPassword())).setResetPassword(false).add(
StringValidator.minimumLength(6)));
form.add(new RequiredTextField<String>("email", MF.m(model, p.getEmail())) {
@Override
protected String getInputType() {
return "email";
}
}.add(RfcCompliantEmailAddressValidator.getInstance()).add(
new IValidator<String>() {
@Override
public void validate(IValidatable<String> validatable) {
String email = validatable.getValue();
User user = userDAO.findByEmail(email);
if (user != null) {
validatable.error(new ValidationError(
"Email is already taken."));
}
}
}));
}.add(RfcCompliantEmailAddressValidator.getInstance()).add(new IValidator<String>() {
@Override
public void validate(IValidatable<String> validatable) {
String email = validatable.getValue();
User user = userDAO.findByEmail(email);
if (user != null) {
validatable.error(new ValidationError("Email is already taken."));
}
}
}));
}
}

View File

@@ -12,8 +12,7 @@ import ro.isdc.wro.model.resource.processor.impl.css.CssImportPreProcessor;
public class SassImportProcessor extends CssImportPreProcessor {
@Override
protected String doTransform(String cssContent, List<Resource> foundImports)
throws IOException {
protected String doTransform(String cssContent, List<Resource> foundImports) throws IOException {
for (Resource resource : foundImports) {
String uri = resource.getUri();
int lastSlash = uri.lastIndexOf('/');

View File

@@ -15,10 +15,8 @@ import ro.isdc.wro.model.resource.SupportedResourceType;
public class SassOnlyProcessor extends RubySassCssProcessor {
@Override
public void process(Resource resource, Reader reader, Writer writer)
throws IOException {
if (resource.getUri().endsWith(".sass")
|| resource.getUri().endsWith(".scss")) {
public void process(Resource resource, Reader reader, Writer writer) throws IOException {
if (resource.getUri().endsWith(".sass") || resource.getUri().endsWith(".scss")) {
super.process(resource, reader, writer);
} else {
writer.write(IOUtils.toString(reader));

View File

@@ -17,8 +17,7 @@ public class TimestampProcessor implements ResourcePreProcessor {
private static final String NOW = "" + System.currentTimeMillis();
@Override
public void process(Resource resource, Reader reader, Writer writer)
throws IOException {
public void process(Resource resource, Reader reader, Writer writer) throws IOException {
String content = IOUtils.toString(reader);
content = content.replace("${timestamp}", NOW);
writer.write(content);

View File

@@ -24,10 +24,8 @@ public abstract class UserCustomCssReference extends ResourceReference {
resourceResponse.setTextEncoding("UTF-8");
resourceResponse.setWriteCallback(new WriteCallback() {
@Override
public void writeData(Attributes attributes)
throws IOException {
attributes.getResponse().write(
StringUtils.trimToEmpty(getCss()));
public void writeData(Attributes attributes) throws IOException {
attributes.getResponse().write(StringUtils.trimToEmpty(getCss()));
}
});
return resourceResponse;

View File

@@ -10,7 +10,7 @@ import com.google.api.client.util.Maps;
/**
* Build-time solution
*
*
*/
public class WroAdditionalProvider implements ProcessorProvider {

View File

@@ -7,7 +7,7 @@ import ro.isdc.wro.model.resource.processor.ResourcePreProcessor;
/**
* Runtime solution
*
*
*/
public class WroManagerFactory extends ConfigurableWroManagerFactory {

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());

View File

@@ -29,14 +29,12 @@ import com.commafeed.backend.services.ApplicationPropertiesService;
import com.commafeed.frontend.CommaFeedSession;
/**
* Replace variables from templates on the fly in dev mode only. In production
* the substitution is done at build-time.
* Replace variables from templates on the fly in dev mode only. In production the substitution is done at build-time.
*
*/
public class InternationalizationDevelopmentFilter implements Filter {
private static Logger log = LoggerFactory
.getLogger(InternationalizationDevelopmentFilter.class);
private static Logger log = LoggerFactory.getLogger(InternationalizationDevelopmentFilter.class);
@Inject
UserSettingsDAO userSettingsDAO;
@@ -55,8 +53,7 @@ public class InternationalizationDevelopmentFilter implements Filter {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if (production) {
chain.doFilter(request, response);
@@ -64,8 +61,7 @@ public class InternationalizationDevelopmentFilter implements Filter {
}
final ServletOutputStream wrapper = new ServletOutputStreamWrapper();
ServletResponse interceptor = new HttpServletResponseWrapper(
(HttpServletResponse) response) {
ServletResponse interceptor = new HttpServletResponseWrapper((HttpServletResponse) response) {
@Override
public ServletOutputStream getOutputStream() throws IOException {
@@ -74,10 +70,8 @@ public class InternationalizationDevelopmentFilter implements Filter {
};
chain.doFilter(request, interceptor);
UserSettings settings = userSettingsDAO.findByUser(CommaFeedSession
.get().getUser());
String lang = (settings == null || settings.getLanguage() == null) ? "en"
: settings.getLanguage();
UserSettings settings = userSettingsDAO.findByUser(CommaFeedSession.get().getUser());
String lang = (settings == null || settings.getLanguage() == null) ? "en" : settings.getLanguage();
byte[] bytes = translate(wrapper.toString(), lang).getBytes("UTF-8");
response.setContentLength(bytes.length);
@@ -91,8 +85,7 @@ public class InternationalizationDevelopmentFilter implements Filter {
Properties props = new Properties();
InputStream is = null;
try {
is = getClass()
.getResourceAsStream("/i18n/" + lang + ".properties");
is = getClass().getResourceAsStream("/i18n/" + lang + ".properties");
props.load(new InputStreamReader(is, "UTF-8"));
} catch (Exception e) {
log.error(e.getMessage(), e);
@@ -111,8 +104,7 @@ public class InternationalizationDevelopmentFilter implements Filter {
while (m.find()) {
String var = m.group(1);
Object replacement = props.get(var);
String replacementValue = replacement == null ? var : replacement
.toString().split("#")[0];
String replacementValue = replacement == null ? var : replacement.toString().split("#")[0];
m.appendReplacement(sb, replacementValue);
}
m.appendTail(sb);

View File

@@ -38,7 +38,7 @@ public class ModelFactory {
*
*/
public static class MF {
public static <T> String i(T proxiedValue) {
return ModelFactory.invokedProperty(proxiedValue);
}

View File

@@ -17,16 +17,12 @@ import org.apache.wicket.util.template.PackageTextTemplate;
public class WicketUtils {
public static void loadJS(IHeaderResponse response, Class<?> klass,
String fileName) {
HeaderItem result = JavaScriptHeaderItem
.forReference(new JavaScriptResourceReference(klass, fileName
+ ".js"));
public static void loadJS(IHeaderResponse response, Class<?> klass, String fileName) {
HeaderItem result = JavaScriptHeaderItem.forReference(new JavaScriptResourceReference(klass, fileName + ".js"));
response.render(result);
}
public static void loadJS(IHeaderResponse response, Class<?> klass,
String fileName, Map<String, ? extends Object> variables) {
public static void loadJS(IHeaderResponse response, Class<?> klass, String fileName, Map<String, ? extends Object> variables) {
HeaderItem result = null;
PackageTextTemplate template = null;
try {
@@ -40,14 +36,12 @@ public class WicketUtils {
}
public static HttpServletRequest getHttpServletRequest() {
ServletWebRequest servletWebRequest = (ServletWebRequest) RequestCycle
.get().getRequest();
ServletWebRequest servletWebRequest = (ServletWebRequest) RequestCycle.get().getRequest();
return servletWebRequest.getContainerRequest();
}
public static HttpServletResponse getHttpServletResponse() {
WebResponse webResponse = (WebResponse) RequestCycle.get()
.getResponse();
WebResponse webResponse = (WebResponse) RequestCycle.get().getResponse();
return (HttpServletResponse) webResponse.getContainerResponse();
}
}

View File

@@ -20,8 +20,7 @@ public class DisplayExceptionPage extends BasePage {
add(new Label("message", t.getMessage()));
add(new BookmarkablePageLink<Void>("homepage", getApplication()
.getHomePage()));
add(new BookmarkablePageLink<Void>("homepage", getApplication().getHomePage()));
StringWriter stringWriter = new StringWriter();
t.printStackTrace(new PrintWriter(stringWriter));