From b044930b49e51ffd25eb1c1ff49c987d7d2b0ea4 Mon Sep 17 00:00:00 2001 From: "John H. Anthony" Date: Sat, 4 Sep 2010 15:05:28 +0200 Subject: 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. --- src/WEB-INF/web.xml | 10 +++++++++ src/lq/AddVote.java | 65 +++++++++++++++++++++++++++++++++++++++++++++++++++++ src/lq/Printer.java | 2 +- 3 files changed, 76 insertions(+), 1 deletion(-) create mode 100644 src/lq/AddVote.java (limited to 'src') diff --git a/src/WEB-INF/web.xml b/src/WEB-INF/web.xml index 432d10a..1fa3dab 100644 --- a/src/WEB-INF/web.xml +++ b/src/WEB-INF/web.xml @@ -16,6 +16,16 @@ /post/add + + add_vote + lq.AddVote + + + + add_vote + /vote + + importquotes lq.ImportQuotes 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)); + } +} diff --git a/src/lq/Printer.java b/src/lq/Printer.java index 573ab5d..beee449 100644 --- a/src/lq/Printer.java +++ b/src/lq/Printer.java @@ -24,7 +24,7 @@ public class Printer { out.println(QuoteUtil.formatScore(quote)); out.println("
Vote: "); for(int nv=1; nv<=5; nv++) - out.println(""+nv+" "); + out.println(""+nv+" "); out.println(" "); out.println("

"); -- cgit v1.2.3