summaryrefslogtreecommitdiff
path: root/src/lq/AddQuote.java
blob: 64498280cdec203ec1a8e08356f378f6b1366abf (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
66
67
68
69
package lq;

import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AddQuote extends HttpServlet {

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws IOException {
      String nick = req.getParameter("nick");
      String text = req.getParameter("quote");
      String date = req.getParameter("date");
      String forward = req.getHeader("X-Forwarded-For");
      String ip = req.getRemoteAddr();

      resp.setContentType("text/html");

      boolean validInput = true;
      Date quoteDate = new Date();

      if (Strings.nullOrEmpty(nick)) {
          nick = "Anonym";
      }
      if (Strings.nullOrEmpty(text)) {
          validInput = false;
      }
      if (!Strings.nullOrEmpty(date)) {
          try {
              quoteDate = DateUtil.dateFormat.parse(date);
          }
          catch (ParseException exception) {
              resp.getWriter().println("Dato må være på formatet YYYY-MM-DD");
              validInput = false;
          }
      }
      if (!Strings.nullOrEmpty(forward)) {
          ip = ip + " (" + forward + ")";
      }

      if (!validInput) {
        resp.getWriter().println("Eskje du lidt kniben nå");
        return;
      }

      Quote newQuote = new Quote(quoteDate, nick, text, ip);
      PersistenceManager pm = PMF.get().getPersistenceManager();
      try {
          pm.makePersistent(newQuote);
      }
      finally {
          pm.close();
      }

      resp.getWriter().println(successString);
    }

  public final String successString = 
          "<center>\n" +
          "<img src=\"/roflcopter.gif\" /><p />\n" +
          "<pre> Takk, quoten venter nå på godkjenning.</pre>\n" +
          "<pre> <a href=\"/quotes.jsp\">Tilbake til quotes</a> </pre>\n" +
          "</center>\n";
}