summaryrefslogtreecommitdiff
path: root/src/lq/AddVote.java
blob: e9a442af439d1b45e331063ef993932eb2b6818f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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));
    }
}