KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > webapps > addressbook > DbAddBook


1 package org.jahia.webapps.addressbook;
2
3 import java.sql.*;
4 import java.io.*;
5 import java.util.*;
6
7 // the OJB stuff...
8
import org.apache.ojb.broker.PersistenceBroker;
9 import org.apache.ojb.broker.*;
10 import org.apache.ojb.broker.query.*;
11 import org.apache.ojb.broker.accesslayer.*;
12
13 import org.jahia.tools.*;
14 import org.jahia.tools.db.*;
15
16
17 /**
18  * Class DbAddBook: represents the address book api for database
19  *
20  * @author Jerome Tamiotti <a HREF="mailto:tamiotti@xo3.com">tamiotti@xo3.com</a>
21  *
22  */

23 public class DbAddBook
24 {
25
26   private AddressBook addbookRef;
27
28   private static String JavaDoc SEPARATOR = ",";
29
30
31   /**
32    * The class constructor
33    *
34    * @param the_add_book the reference to the in-memory address book
35    */

36   public DbAddBook (AddressBook addbook) {
37
38     // set the reference to address book
39
this.addbookRef = addbook;
40   }
41
42
43
44
45
46
47
48     /**
49      * Insert a new contact in the database
50      *
51      * @param newContact the contact to insert
52      * @return the id of this new contact
53      */

54     public int insert (Contact newContact) {
55
56       int max = 0;
57
58       Tools.toConsole("Dbaddbook: Insert", "Begin");
59       // get max id
60

61         max = AdbApplicationDB.getNextId("contact_id","contact");
62         newContact.setId(max);
63         AdbApplicationDB.insertContact(newContact);
64         return max;
65
66     }
67
68
69     /**
70      * Remove a contact from the database
71      *
72      * @param contactId the id of the contact to remove
73      */

74     public void delete (int contactId) {
75
76       // check if the contact is a company : if so, update all the contacts
77
// whose company field was the id of this company
78
try {
79        // ResultSet rs = AdbApplicationDB.executeQuery("select civil_title, last_name from contact where contact_id=" + contactId);
80
Contact c= AdbApplicationDB.SearchContactById(contactId);
81        if (!c.equals(null)) {
82          String JavaDoc civilTitle = c.getCivilTitle();
83          if (civilTitle.equals("Company")) {
84            String JavaDoc companyName = c.getLastName();
85            AdbApplicationDB.updateCompany(contactId,companyName);
86            // StringBuffer sql = new StringBuffer("update contact set company='");
87
//sql.append(companyName);
88
//sql.append("' where company=");
89
//sql.append(contactId);
90
Tools.toConsole("DbAddBook : delete");
91            // AdbApplicationDB.executeQuery(sql.toString());
92
}
93        }
94       // AdbApplicationDB.executeQuery("delete from contact where contact_id=" + contactId);
95

96       } catch (Exception JavaDoc e) {
97         Tools.toConsole("DbAddBook : delete",e.toString());
98       }
99     }
100
101
102     /**
103      * Update a contact in the database
104      *
105      * @param id the id of the contact to update
106      * @param contact a contact containing all the new values
107      */

108     public void update (int id, Contact newContact) {
109       AdbApplicationDB.update(id,newContact);
110     }
111
112
113
114     private static String JavaDoc toExportFormat(String JavaDoc input) {
115         if (input == null) {
116           return null;
117         }
118         StringBuffer JavaDoc sb = new StringBuffer JavaDoc(input);
119         if (input.indexOf(",") != -1) {
120           String JavaDoc result = Tools.replace(input, "\"", "\"\"");
121           return "\"" + result + "\"";
122         } else {
123           return input;
124         }
125     }
126
127     /**
128      * Method save : save the content of the address book in a flat file
129      *
130      * @param filepath the full path of the file to create
131      */

132     public void save(String JavaDoc filename) {
133
134       // FIXME: check there's no SEPARATOR in the fields
135
String JavaDoc sql = "select * from contact where addbook_id=" + this.addbookRef.getId();
136       try {
137         ResultSet rs = AdbApplicationDB.executeQuery(sql);
138
139         PrintWriter out = new PrintWriter(new FileWriter(filename));
140         ResultSetMetaData rsmd = rs.getMetaData();
141         int numberOfColumns = rsmd.getColumnCount();
142         for(int i = 1; i <= numberOfColumns; i++) {
143           out.print(toExportFormat(rsmd.getColumnName(i)) + SEPARATOR);
144         }
145         out.print("\n");
146         int nb = 0;
147         while (rs.next()) {
148
149           for(int i = 1; i <= numberOfColumns; i++) {
150
151             String JavaDoc column = rsmd.getColumnName(i).toLowerCase();
152             if (column.startsWith("comm_id_")) {
153               String JavaDoc table = column.substring(0,column.length()-5);
154              // Character c= table[0].toUppercase();
155
String JavaDoc provisoire= table.substring(1);
156               //String classe= c.concat(provisoire);
157
out.print(toExportFormat(readData(table,rs.getInt(column))) + SEPARATOR);
158
159             } else if (column.equals("company")) {
160               String JavaDoc company = rs.getString(column);
161               // check if it's an id or a name
162
try {
163                 int comp_id = Integer.parseInt(company);
164                 Contact tmp = AdbApplicationDB.SearchContactById(comp_id);
165                 company = tmp.getLastName();
166               } catch(NumberFormatException JavaDoc nfe) {
167                 // nothing to do, company is not a reference to an existing contact
168
}
169               out.print(toExportFormat(company) + SEPARATOR);
170
171             } else {
172               out.print(toExportFormat(rs.getString(column)) + SEPARATOR);
173             }
174           }
175           out.print("\n");
176           nb++;
177         }
178         out.close();
179         Tools.toConsole("DbAddBook: save","File saved : " + nb + " contacts has been written");
180
181       } catch (SQLException sqle) {
182         Tools.toConsole("DbAddBook: save","Can't read address book content: "+sqle.toString());
183       } catch (IOException ioe) {
184         Tools.toConsole("DbAddBook: save","Can't write to file: "+ioe.toString());
185       }
186     }
187
188
189     /**
190      * Select all the companies recorded in the addressbook
191      *
192      * @return a vector containing the companies as contacts
193      */

194     public Vector readCompanies () {
195       Vector companies = new Vector();
196       companies= AdbApplicationDB.readCompanies(this.addbookRef.getId());
197
198     //sql.append(" order by lower(company)");
199

200
201     return companies;
202
203
204   }
205
206
207   /**
208      * Read a data label given its id and its table id
209      *
210      * @param table_id the table to read
211      * @param id the data id to find
212      *
213      * @return a string containing data label
214      */

215     public String JavaDoc readData(String JavaDoc table, int id) {
216
217       String JavaDoc ids = table + "_id";
218       String JavaDoc resultat=null;
219     // String resultat= AdbApplicationDB.readData(ids,id,classe);
220
//StringBuffer sql = new StringBuffer("select label from ");
221
//sql.append(table);
222
//sql.append(" where ");
223
//sql.append(ids);
224
//sql.append("='");
225
//sql.append(id);
226
//sql.append("'");
227
return resultat;
228     }
229
230
231
232
233
234     /**
235      * Method renameCategory: rename an existing category
236      *
237      * @param cat_id the id of the category to rename
238      * @param cat_name the new name for the category
239      */

240     public static void renameCategory(int cat_id, String JavaDoc cat_name) {
241
242             AdbApplicationDB.renameCategory(cat_id, cat_name );
243         //AdbApplicationDB.executeQuery("update category set label='" + Tools.Quote(cat_name) + "' where category_id=" + cat_id);
244

245       }
246
247
248     /**
249      * Method deleteCategory: delete an existing category
250      *
251      * @param cat_id the id of the category to delete
252      */

253     public static void deleteCategory(int cat_id) {
254           try {
255         AdbApplicationDB.executeQuery("delete from category where category_id=" + cat_id);
256         AdbApplicationDB.executeQuery("update contact set category_id=-1 where category_id=" + cat_id);
257           }catch (SQLException e) {}
258     }
259
260
261
262
263 }
264
Popular Tags