package hirondelle.fish.main.discussion;
import hirondelle.web4j.BuildImpl;
import hirondelle.web4j.action.ActionTemplateShowAndApply;
import hirondelle.web4j.action.ResponsePage;
import hirondelle.web4j.database.DAOException;
import hirondelle.web4j.database.Db;
import hirondelle.web4j.database.SqlId;
import hirondelle.web4j.model.AppException;
import hirondelle.web4j.model.ModelCtorException;
import hirondelle.web4j.model.ModelFromRequest;
import hirondelle.web4j.request.RequestParameter;
import hirondelle.web4j.request.RequestParser;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;
public final class CommentAction extends ActionTemplateShowAndApply {
public static final SqlId FETCH_RECENT_COMMENTS = new SqlId("FETCH_RECENT_COMMENTS");
public static final SqlId ADD_COMMENT = new SqlId("ADD_COMMENT");
public CommentAction(RequestParser aRequestParser){
super(FORWARD, REDIRECT, aRequestParser);
}
public static final RequestParameter COMMENT_BODY = RequestParameter.withLengthCheck(
"Comment Body"
);
public static final RequestParameter PAGE_SIZE = RequestParameter.withRegexCheck(
"PageSize", Pattern.compile("(\\d){1,4}")
);
public static final RequestParameter PAGE_INDEX = RequestParameter.withRegexCheck(
"PageIndex", Pattern.compile("(\\d){1,4}")
);
protected void show() throws AppException {
addToRequest(ITEMS_FOR_LISTING, fetchRecentComments());
}
protected void validateUserInput() throws AppException {
try {
ModelFromRequest builder = new ModelFromRequest(getRequestParser());
long now = BuildImpl.forTimeSource().currentTimeMillis();
fComment = builder.build(
Comment.class, getLoggedInUserName(), COMMENT_BODY, new Date(now)
);
}
catch (ModelCtorException ex){
addError(ex);
}
}
protected void apply() throws AppException {
addNew(fComment);
}
private Comment fComment;
private static final ResponsePage FORWARD = new ResponsePage(
"Discussion", "view.jsp", CommentAction.class
);
private static final ResponsePage REDIRECT = new ResponsePage(
"CommentAction.show?PageIndex=1&PageSize=10"
);
private List<Comment> fetchRecentComments() throws DAOException {
return Db.list(Comment.class, FETCH_RECENT_COMMENTS);
}
private void addNew(Comment aNewComment) throws DAOException {
Object[] params = {
aNewComment.getUserName(), aNewComment.getBody(), aNewComment.getDate()
};
Db.edit(ADD_COMMENT, params);
}
}