d01861ca2aef16891a15bb7f31cdd1067978ffa4
[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.Collection;
39 import java.util.Iterator;
40
41 import mir.entity.EntityList;
42 import mir.log.LoggerWrapper;
43 import mir.storage.Database;
44 import mir.storage.StorageObject;
45 import mir.storage.StorageObjectFailure;
46 import mircoders.entity.EntityContent;
47 import mircoders.entity.EntityTopics;
48
49 /**
50  * <b>This class implements the 1-n-relation between
51  * content and topic
52  *
53  */
54
55 public class DatabaseContentToTopics extends Database implements StorageObject{
56
57   private static DatabaseContentToTopics instance;
58
59   // the following *has* to be sychronized cause this static method
60   // could get preemted and we could end up with 2 instances of DatabaseFoo.
61   // see the "Singletons with needles and thread" article at JavaWorld -mh
62   public synchronized static DatabaseContentToTopics getInstance()
63     throws StorageObjectFailure {
64     if (instance == null) {
65       instance = new DatabaseContentToTopics();
66       instance.myselfDatabase = instance;
67     }
68     return instance;
69   }
70
71   private DatabaseContentToTopics() throws StorageObjectFailure {
72     super();
73
74     logger = new LoggerWrapper("Database.ContentToTopics");
75
76     hasTimestamp = false;
77     theTable="content_x_topic";
78     try { this.theEntityClass = Class.forName("mir.entity.GenericEntity"); }
79     catch (Exception e) { throw new StorageObjectFailure(e); }
80
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 ArrayList 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   /**
138    * Set new topics
139    */
140   public void setTopics(String contentId, String[] topicId)
141     throws StorageObjectFailure {
142     if (contentId == null){
143       return;
144     }
145     if (topicId==null || topicId[0]==null) {
146       return;
147     }
148     //first check which topics this article has
149     Collection hasTopics = getTopicsOfContent(contentId);
150     Collection toSet = new ArrayList();
151     Collection toDelete = new ArrayList();
152
153     if(hasTopics!=null && hasTopics.size()>0){
154       //now we check if there are new topics and copy them to an array.
155       for(int i = 0; i< topicId.length;i++){
156         boolean set=false;
157         int whichTopic = 0;
158         for(Iterator it=hasTopics.iterator();it.hasNext();){
159           Integer topic = (Integer)it.next();
160           if(topicId[i].equals(topic.toString())){
161             set=true;
162           } else {
163             whichTopic = i;
164           }
165         }
166         if(set==false){
167           toSet.add(topicId[i]);
168           logger.debug("to set: "+ topicId[i]);
169         }
170       }
171       //now we check if we have to delete topics
172       for(Iterator it=hasTopics.iterator();it.hasNext();){
173         boolean delete=true;
174         int whichTopic = 0;
175         Integer topic = (Integer)it.next();
176         for(int i = 0; i< topicId.length;i++){
177           if(topicId[i].equals(topic.toString())){
178             delete=false;
179           } else {
180             whichTopic = i;
181           }
182         }
183         if(delete==true){
184           toDelete.add(topic.toString());
185           logger.debug("to delete: "+ topic.toString());
186         }
187       }
188     } else {
189       //all the topics has to be set, so we copy all to the array
190                         for (int i = 0; i < topicId.length; i++){
191                                 toSet.add(topicId[i]);
192                         }
193     }
194
195     //first delete all row with content_id=contentId
196     String sql = "delete from "+ theTable +" where content_id=" + contentId
197                 + " and topic_id in (";
198     boolean first=false;
199     for(Iterator it = toDelete.iterator(); it.hasNext();){
200       if(first==false){
201         first=true;
202       } else {
203         sql+=",";
204       }
205       sql+= (String)it.next();
206     }
207     sql+=")";
208     Connection con=null;Statement stmt=null;
209     try {
210       con = getPooledCon();
211       // should be a preparedStatement because is faster
212       stmt = con.createStatement();
213       int rs = executeUpdate(stmt,sql);
214     } catch (Exception e) {
215       logger.error("-- deleting topics failed");
216     } finally {
217       freeConnection(con,stmt);
218     }
219
220     //now insert
221     //first delete all row with content_id=contentId
222     for (Iterator it = toSet.iterator(); it.hasNext();) {
223       sql = "insert into "+ theTable +" (content_id,topic_id) values ("
224             + contentId + "," + (String)it.next() + ")";
225       try {
226         con = getPooledCon();
227         // should be a preparedStatement because is faster
228         stmt = con.createStatement();
229         int rs = executeUpdate(stmt,sql);
230       }
231       catch (Exception e) {
232         logger.error("-- set topics failed -- insert laenge topicId" + topicId.length);
233       } finally {
234         freeConnection(con,stmt);
235       }
236     }
237   }
238
239   public void deleteByContentId(String contentId)
240     throws StorageObjectFailure {
241     if (contentId == null) {
242       //theLog.printDebugInfo("-- delete topics failed -- no content id");
243       return;
244     }
245     //delete all row with content_id=contentId
246     String sql = "delete from "+ theTable +" where content_id=" + contentId;
247
248     Connection con=null;Statement stmt=null;
249     try {
250       con = getPooledCon();
251       // should be a preparedStatement because is faster
252       stmt = con.createStatement();
253       ResultSet rs = executeSql(stmt,sql);
254     } catch (Exception e) {
255       //theLog.printDebugInfo("-- delete topics failed  ");
256     } finally {
257       freeConnection(con,stmt);
258     }
259   }
260
261   public void deleteByTopicId(String topicId)
262     throws StorageObjectFailure {
263     if (topicId == null) {
264       //theLog.printDebugInfo("-- delete topics failed -- no topic id");
265       return;
266     }
267     //delete all row with content_id=contentId
268     String sql = "delete from "+ theTable +" where topic_id=" + topicId;
269
270     Connection con=null;Statement stmt=null;
271     try {
272       con = getPooledCon();
273       // should be a preparedStatement because is faster
274       stmt = con.createStatement();
275       ResultSet rs = executeSql(stmt,sql);
276     }
277     catch (Exception e) {
278       logger.error("-- delete topics failed ");
279     }
280     finally {
281       freeConnection(con,stmt);
282     }
283   }
284
285
286   public EntityList getContent(EntityTopics topic)
287     throws StorageObjectFailure {
288     EntityList returnList=null;
289     if (topic != null) {
290       String id = topic.getId();
291       String select = "select content_id from " + theTable + " where topic_id=" + id;
292
293       // execute select statement
294       Connection con=null;Statement stmt=null;
295       try {
296         con = getPooledCon();
297         // should be a preparedStatement because is faster
298         stmt = con.createStatement();
299         ResultSet rs = executeSql(stmt,select);
300         if (rs!=null) {
301           String topicSelect= "id IN (";
302           boolean first=true;
303           while (rs.next()) {
304             if (first==false) topicSelect+=",";
305             topicSelect += rs.getString(1);
306             first=false;
307           }
308           topicSelect+=")";
309           if (first==false)
310             returnList = DatabaseContent.getInstance().selectByWhereClause(topicSelect,-1);
311         }
312       }
313       catch (Exception e) {
314         logger.error("-- get contetn failed");
315       }
316       finally { freeConnection(con,stmt);}
317     }
318     return returnList;
319   }
320 }