1 package org.melati.example.contacts;
2
3 import java.io.IOException;
4
5 import org.melati.Melati;
6 import org.melati.servlet.Form;
7 import org.melati.PoemContext;
8 import org.melati.servlet.PathInfoException;
9 import org.melati.template.ServletTemplateContext;
10
11
12
13
14
15
16 public class ContactView extends ContactsServlet {
17 private static final long serialVersionUID = 1L;
18
19 protected String doTemplateRequest(Melati melati, ServletTemplateContext context)
20 throws Exception {
21
22 ContactsDatabase db = (ContactsDatabase)melati.getDatabase();
23 Contact contact = (Contact)melati.getObject();
24
25 if (melati.getMethod().equals("Insert")) {
26 contact = (Contact)db.getContactTable().newPersistent();
27 }
28
29 else if (melati.getMethod().equals("Update")) {
30 if (contact == null) {
31 contact = (Contact) db.getContactTable().newPersistent();
32 Form.extractFields(melati.getServletTemplateContext(),contact);
33 db.getContactTable().create(contact);
34 } else {
35 Form.extractFields(melati.getServletTemplateContext(),contact);
36 }
37 deleteCategories(db,contact);
38
39 String[] categories = melati.getRequest().
40 getParameterValues("field_category");
41 if (categories != null) {
42 for (int i=0; i< categories.length; i++) {
43 ContactCategory cat =
44 (ContactCategory)db.getContactCategoryTable().newPersistent();
45 cat.setContact(contact);
46 cat.setCategoryTroid(new Integer(categories[i]));
47 db.getContactCategoryTable().create(cat);
48 }
49 }
50 try {
51 melati.getResponse().sendRedirect
52 (melati.getZoneURL() + "/org.melati.example.contacts.Search/contacts");
53 } catch (IOException e) {
54 throw new Exception(e.toString());
55 }
56 return null;
57 }
58
59 else if (melati.getMethod().equals("Delete")) {
60 deleteCategories(db,contact);
61 contact.deleteAndCommit();
62 try {
63 melati.getResponse().sendRedirect
64 (melati.getZoneURL() + "/org.melati.example.contacts.Search/contacts");
65 } catch (IOException e) {
66 throw new Exception(e.toString());
67 }
68 return null;
69 }
70 else if (melati.getMethod().equals("View")) {
71 }
72 else {
73 throw new Exception("Invalid Method");
74 }
75 context.put("contact",contact);
76 context.put("categories",db.getCategoryTable().selection());
77
78 return "org/melati/example/contacts/ContactView";
79 }
80
81
82
83
84
85
86
87 public void deleteCategories(ContactsDatabase db, Contact contact) {
88
89 db.sqlUpdate("DELETE FROM " + db.quotedName("contactcategory") +
90 " WHERE " + db.quotedName("contact") + " = " +
91 contact.getTroid());
92 }
93
94 protected PoemContext poemContext(Melati melati)
95 throws PathInfoException {
96 return poemContextWithLDB(melati,"contacts");
97 }
98
99 }
100
101