fbf46e228bf3e5dbdfc8fdfc866d2fdac155d62d
[mir.git] / source / mircoders / storage / DatabaseContentToTopics.java
1 /*
2  * Copyright (C) 2001, 2002  The Mir-coders group
3  *
4  * This file is part of Mir.
5  *
6  * Mir is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * Mir is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with Mir; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  * In addition, as a special exception, The Mir-coders gives permission to link
21  * the code of this program with the com.oreilly.servlet library, any library
22  * licensed under the Apache Software License, The Sun (tm) Java Advanced
23  * Imaging library (JAI), The Sun JIMI library (or with modified versions of
24  * the above that use the same license as the above), and distribute linked
25  * combinations including the two.  You must obey the GNU General Public
26  * License in all respects for all of the code used other than the above
27  * mentioned libraries.  If you modify this file, you may extend this exception
28  * to your version of the file, but you are not obligated to do so.  If you do
29  * not wish to do so, delete this exception statement from your version.
30  */
31
32 package mircoders.storage;
33
34 import java.sql.Connection;
35 import java.sql.ResultSet;
36 import java.sql.Statement;
37 import java.util.ArrayList;
38 import java.util.Arrays;
39 import java.util.Iterator;
40 import java.util.List;
41 import java.util.Vector;
42
43 import mir.entity.EntityList;
44 import mir.log.LoggerWrapper;
45 import mir.storage.Database;
46 import mir.storage.StorageObject;
47 import mir.storage.StorageObjectFailure;
48 import mircoders.entity.EntityContent;
49 import mircoders.entity.EntityTopics;
50
51 /**
52  * <b>This class implements the 1-n-relation between
53  * content and topic
54  *
55  */
56
57 public class DatabaseContentToTopics extends Database implements StorageObject{
58
59   private static DatabaseContentToTopics instance;
60
61   public static DatabaseContentToTopics getInstance() {
62     if (instance == null) {
63       synchronized (DatabaseContentToTopics.class) {
64         if (instance == null) {
65           instance = new DatabaseContentToTopics();
66           instance.myselfDatabase = instance;
67         }
68       }
69     }
70     return instance;
71   }
72
73   private DatabaseContentToTopics() {
74     super();
75
76     logger = new LoggerWrapper("Database.ContentToTopics");
77
78     hasTimestamp = false;
79     theTable="content_x_topic";
80     theEntityClass = mir.entity.GenericEntity.class;
81   }
82
83   /**
84    * This class return an EntityList of Topics
85    * @param EntityContent content
86    * @returns EntityList
87    */
88   public EntityList getTopics(EntityContent content) {
89     EntityList returnList=null;
90     if (content != null) {
91       // get all to_topic from content_x_topic
92       String id = content.getId();
93       String subselect = "id in (select topic_id from " + theTable + " where content_id=" + id+")";
94
95       try {
96         returnList = DatabaseTopics.getInstance().selectByWhereClause(subselect,-1);
97       }
98       catch (Exception e) {
99         logger.error("-- get topics failed " + e.toString());
100       }
101     }
102     return returnList;
103   }
104
105   /**
106    * Returns a ArrayList of Integer-Objects from a content-id.
107    * @returns ArrayList
108    */
109   public List getTopicsOfContent(String contentId)
110     throws StorageObjectFailure {
111     ArrayList returnList = new ArrayList();
112
113     if (contentId != null) {
114       String sql = "select topic_id from " + theTable + " where content_id=" + contentId;
115       Connection con=null;Statement stmt=null;
116       try {
117         con = getPooledCon();
118         // should be a preparedStatement because is faster
119         stmt = con.createStatement();
120         ResultSet rs = executeSql(stmt,sql);
121         if(rs!=null){
122           while(rs.next()){
123             returnList.add(new Integer(rs.getInt("topic_id")));
124           }
125         }
126       }
127       catch (Exception e) {
128         logger.error("DatabaseContentToTopics.getTopicsOfContent: " + e.getMessage());
129       }
130       finally {
131         freeConnection(con,stmt);
132       }
133     }
134     return returnList;
135   }
136
137   private String getIdListExpression(List aList) {
138     String result = "";
139
140     Iterator i = aList.iterator();
141
142     while (i.hasNext()) {
143       result = result + i.next().toString();
144       if (i.hasNext())
145         result = result + ", ";
146     }
147     return result;
148   }
149
150   public void setTopics(String anArticleId, String [] aTopics) throws StorageObjectFailure {
151     if (aTopics==null)
152       setTopics(anArticleId, (List) null);
153     else
154       setTopics(anArticleId, Arrays.asList(aTopics));
155   }
156
157   public void setTopics(String anArticleId, List aTopics) throws StorageObjectFailure {
158     List newTopics = new Vector();
159     if (aTopics!=null) {
160       Iterator i = aTopics.iterator();
161
162       while (i.hasNext()) {
163         newTopics.add(new Integer(Integer.parseInt((String) i.next())));
164       }
165     }
166
167     List currentTopics = getTopicsOfContent(anArticleId);
168     logger.debug("New topics = " + newTopics.toString());
169     logger.debug("Current topics = " + currentTopics.toString());
170     List topicsToDelete = new Vector(currentTopics);
171     topicsToDelete.removeAll(newTopics);
172     List topicsToAdd = new Vector(newTopics);
173     topicsToAdd.removeAll(currentTopics);
174     logger.debug("to delete = " + topicsToDelete.toString());
175     logger.debug("to add = " + topicsToAdd.toString());
176
177
178     if (!topicsToDelete.isEmpty()) {
179       String sql =
180           "delete from " + theTable + " " +
181           "where content_id=" + anArticleId +
182           "        and topic_id in (" + getIdListExpression(topicsToDelete) + ")";
183
184       Connection connection=null;
185       Statement statement=null;
186       try {
187         connection = getPooledCon();
188         statement = connection.createStatement();
189         int rs = executeUpdate(statement, sql);
190       }
191       catch (Exception e) {
192         logger.error("-- deleting topics failed");
193       }
194       finally {
195         try {
196           freeConnection(connection, statement);
197         }
198         catch (Throwable t) {
199         }
200       }
201     }
202
203     Iterator i = topicsToAdd.iterator();
204     while (i.hasNext()) {
205       Integer topicId = (Integer) i.next();
206       String sql =
207           "insert into " + theTable + " (content_id, topic_id) "+
208           "values (" + anArticleId + "," + topicId + ")";
209       Connection connection=null;
210       Statement statement=null;
211       try {
212         connection = getPooledCon();
213         // should be a preparedStatement because is faster
214         statement = connection.createStatement();
215         int rs = executeUpdate(statement, sql);
216       }
217       catch (Exception e) {
218         logger.error("-- adding topics failed");
219       }
220       finally {
221         try {
222           freeConnection(connection, statement);
223         }
224         catch (Throwable t) {
225         }
226       }
227     }
228   }
229
230   public void deleteByContentId(String contentId)
231     throws StorageObjectFailure {
232     if (contentId == null) {
233       //theLog.printDebugInfo("-- delete topics failed -- no content id");
234       return;
235     }
236     //delete all row with content_id=contentId
237     String sql = "delete from "+ theTable +" where content_id=" + contentId;
238
239     Connection con=null;Statement stmt=null;
240     try {
241       con = getPooledCon();
242       // should be a preparedStatement because is faster
243       stmt = con.createStatement();
244       ResultSet rs = executeSql(stmt,sql);
245     } catch (Exception e) {
246       //theLog.printDebugInfo("-- delete topics failed  ");
247     } finally {
248       freeConnection(con,stmt);
249     }
250   }
251
252   public void deleteByTopicId(String topicId)
253     throws StorageObjectFailure {
254     if (topicId == null) {
255       //theLog.printDebugInfo("-- delete topics failed -- no topic id");
256       return;
257     }
258     //delete all row with content_id=contentId
259     String sql = "delete from "+ theTable +" where topic_id=" + topicId;
260
261     Connection con=null;Statement stmt=null;
262     try {
263       con = getPooledCon();
264       // should be a preparedStatement because is faster
265       stmt = con.createStatement();
266       ResultSet rs = executeSql(stmt,sql);
267     }
268     catch (Exception e) {
269       logger.error("-- delete topics failed ");
270     }
271     finally {
272       freeConnection(con,stmt);
273     }
274   }
275
276
277   public EntityList getContent(EntityTopics topic)
278     throws StorageObjectFailure {
279     EntityList returnList=null;
280     if (topic != null) {
281       String id = topic.getId();
282       String select = "select content_id from " + theTable + " where topic_id=" + id;
283
284       // execute select statement
285       Connection con=null;Statement stmt=null;
286       try {
287         con = getPooledCon();
288         // should be a preparedStatement because is faster
289         stmt = con.createStatement();
290         ResultSet rs = executeSql(stmt,select);
291         if (rs!=null) {
292           String topicSelect= "id IN (";
293           boolean first=true;
294           while (rs.next()) {
295             if (first==false) topicSelect+=",";
296             topicSelect += rs.getString(1);
297             first=false;
298           }
299           topicSelect+=")";
300           if (first==false)
301             returnList = DatabaseContent.getInstance().selectByWhereClause(topicSelect,-1);
302         }
303       }
304       catch (Exception e) {
305         logger.error("-- get contetn failed");
306       }
307       finally { freeConnection(con,stmt);}
308     }
309     return returnList;
310   }
311 }