diff options
author | John H. Anthony <johnhant@gmail.com> | 2010-09-04 15:05:28 +0200 |
---|---|---|
committer | John H. Anthony <johnhant@gmail.com> | 2010-09-04 15:05:28 +0200 |
commit | b044930b49e51ffd25eb1c1ff49c987d7d2b0ea4 (patch) | |
tree | e08fec1b9f85a862aa40e5105f73b41c6fbe1ae5 /src/lq/AddVote.java | |
parent | c35a035d25b06bc7ad403ec82dd4495056e599d7 (diff) |
implemented voting
Voting now appears to work, using the AddVote servlet. The datastore
update is not committed as a transaction yet; the quote and its votes
has to be in the same entity group for transactions to work.
Diffstat (limited to 'src/lq/AddVote.java')
-rw-r--r-- | src/lq/AddVote.java | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/src/lq/AddVote.java b/src/lq/AddVote.java new file mode 100644 index 0000000..e9a442a --- /dev/null +++ b/src/lq/AddVote.java @@ -0,0 +1,65 @@ +package lq; + +import java.io.IOException; +import javax.jdo.PersistenceManager; +import javax.jdo.Transaction; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +public class AddVote extends HttpServlet { + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws IOException { + + resp.setContentType("text/html"); + + Long quoteId; + Long rating; + String ip; + + try { + quoteId = Long.parseLong(req.getParameter("id")); + rating = Long.parseLong(req.getParameter("vote")); + ip = req.getRemoteAddr(); + + String forward = req.getHeader("X-Forwarded-For"); + if (!Strings.nullOrEmpty(forward)) { + ip = ip + " (" + forward + ")"; + } + } catch (NumberFormatException e) { + resp.getWriter().println("invalid arguments"); + return; + } + + if (rating.longValue() < 0 || rating.longValue() > 5) { + resp.getWriter().println("nice try"); + return; + } + + Quote quote = QuoteUtil.getQuoteWithId(quoteId); + if (quote == null) { + resp.getWriter().println("failed to retrieve quote"); + return; + } + + Vote vote = new Vote(quoteId, rating, ip); + QuoteUtil.addVote(quote, vote); + + PersistenceManager pm = PMF.get().getPersistenceManager(); + // Transaction tx = pm.currentTransaction(); + try { + // tx.begin(); + pm.makePersistent(quote); + pm.makePersistent(vote); + // tx.commit(); + } finally { + // if (tx.isActive()) { + // tx.rollback(); + // } + pm.close(); + } + + resp.getWriter().println(QuoteUtil.formatScore(quote)); + } +} |