9bf656001ed8e9350db1562a096091649ef90310
[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   public static DatabaseContentToTopics getInstance() {
60     if (instance == null) {
61       synchronized (DatabaseContentToTopics.class) {
62         if (instance == null) {
63           instance = new DatabaseContentToTopics();
64           instance.myselfDatabase = instance;
65         }
66       }
67     }
68     return instance;
69   }
70
71   private DatabaseContentToTopics() {
72     super();
73
74     logger = new LoggerWrapper("Database.ContentToTopics");
75
76     hasTimestamp = false;
77     theTable="content_x_topic";
78     theEntityClass = mir.entity.GenericEntity.class;
79   }
80
81   /**
82    * This class return an EntityList of Topics
83    * @param EntityContent content
84    * @returns EntityList
85    */
86   public EntityList getTopics(EntityContent content) {
87     EntityList returnList=null;
88     if (content != null) {
89       // get all to_topic from content_x_topic
90       String id = content.getId();
91       String subselect = "id in (select topic_id from " + theTable + " where content_id=" + id+")";
92
93       try {
94         returnList = DatabaseTopics.getInstance().selectByWhereClause(subselect,-1);
95       }
96       catch (Exception e) {
97         logger.error("-- get topics failed " + e.toString());
98       }
99     }
100     return returnList;
101   }
102
103   /**
104    * Returns a ArrayList of Integer-Objects from a content-id.
105    * @returns ArrayList
106    */
107   public ArrayList getTopicsOfContent(String contentId)
108     throws StorageObjectFailure {
109     ArrayList returnList = new ArrayList();
110
111     if (contentId != null) {
112       String sql = "select topic_id from " + theTable + " where content_id=" + contentId;
113       Connection con=null;Statement stmt=null;
114       try {
115         con = getPooledCon();
116         // should be a preparedStatement because is faster
117         stmt = con.createStatement();
118         ResultSet rs = executeSql(stmt,sql);
119         if(rs!=null){
120           while(rs.next()){
121             returnList.add(new Integer(rs.getInt("topic_id")));
122           }
123         }
124       }
125       catch (Exception e) {
126         logger.error("DatabaseContentToTopics.getTopicsOfContent: " + e.getMessage());
127       }
128       finally {
129         freeConnection(con,stmt);
130       }
131     }
132     return returnList;
133   }
134
135   /**
136    * Set new topics
137    */
138   public void setTopics(String contentId, String[] topicId)
139     throws StorageObjectFailure {
140     if (contentId == null){
141       return;
142     }
143     if (topicId==null || topicId[0]==null) {
144       return;
145     }
146     //first check which topics this article has
147     Collection hasTopics = getTopicsOfContent(contentId);
148     Collection toSet = new ArrayList();
149     Collection toDelete = new ArrayList();
150
151     if(hasTopics!=null && hasTopics.size()>0){
152       //now we check if there are new topics and copy them to an array.
153       for(int i = 0; i< topicId.length;i++){
154         boolean set=false;
155         int whichTopic = 0;
156         for(Iterator it=hasTopics.iterator();it.hasNext();){
157           Integer topic = (Integer)it.next();
158           if(topicId[i].equals(topic.toString())){
159             set=true;
160           } else {
161             whichTopic = i;
162           }
163         }
164         if(set==false){
165           toSet.add(topicId[i]);
166           logger.debug("to set: "+ topicId[i]);
167         }
168       }
169       //now we check if we have to delete topics
170       for(Iterator it=hasTopics.iterator();it.hasNext();){
171         boolean delete=true;
172         int whichTopic = 0;
173         Integer topic = (Integer)it.next();
174         for(int i = 0; i< topicId.length;i++){
175           if(topicId[i].equals(topic.toString())){
176             delete=false;
177           } else {
178             whichTopic = i;
179           }
180         }
181         if(delete==true){
182           toDelete.add(topic.toString());
183           logger.debug("to delete: "+ topic.toString());
184         }
185       }
186     } else {
187       //all the topics has to be set, so we copy all to the array
188                         for (int i = 0; i < topicId.length; i++){
189                                 toSet.add(topicId[i]);
190                         }
191     }
192
193     //first delete all row with content_id=contentId
194     String sql = "delete from "+ theTable +" where content_id=" + contentId
195                 + " and topic_id in (";
196     boolean first=false;
197     for(Iterator it = toDelete.iterator(); it.hasNext();){
198       if(first==false){
199         first=true;
200       } else {
201         sql+=",";
202       }
203       sql+= (String)it.next();
204     }
205     sql+=")";
206     Connection con=null;Statement stmt=null;
207     try {
208       con = getPooledCon();
209       // should be a preparedStatement because is faster
210       stmt = con.createStatement();
211       int rs = executeUpdate(stmt,sql);
212     } catch (Exception e) {
213       logger.error("-- deleting topics failed");
214     } finally {
215       freeConnection(con,stmt);
216     }
217
218     //now insert
219     //first delete all row with content_id=contentId
220     for (Iterator it = toSet.iterator(); it.hasNext();) {
221       sql = "insert into "+ theTable +" (content_id,topic_id) values ("
222             + contentId + "," + (String)it.next() + ")";
223       try {
224         con = getPooledCon();
225         // should be a preparedStatement because is faster
226         stmt = con.createStatement();
227         int rs = executeUpdate(stmt,sql);
228       }
229       catch (Exception e) {
230         logger.error("-- set topics failed -- insert laenge topicId" + topicId.length);
231       } finally {
232         freeConnection(con,stmt);
233       }
234     }
235   }
236
237   public void deleteByContentId(String contentId)
238     throws StorageObjectFailure {
239     if (contentId == null) {
240       //theLog.printDebugInfo("-- delete topics failed -- no content id");
241       return;
242     }
243     //delete all row with content_id=contentId
244     String sql = "delete from "+ theTable +" where content_id=" + contentId;
245
246     Connection con=null;Statement stmt=null;
247     try {
248       con = getPooledCon();
249       // should be a preparedStatement because is faster
250       stmt = con.createStatement();
251       ResultSet rs = executeSql(stmt,sql);
252     } catch (Exception e) {
253       //theLog.printDebugInfo("-- delete topics failed  ");
254     } finally {
255       freeConnection(con,stmt);
256     }
257   }
258
259   public void deleteByTopicId(String topicId)
260     throws StorageObjectFailure {
261     if (topicId == null) {
262       //theLog.printDebugInfo("-- delete topics failed -- no topic id");
263       return;
264     }
265     //delete all row with content_id=contentId
266     String sql = "delete from "+ theTable +" where topic_id=" + topicId;
267
268     Connection con=null;Statement stmt=null;
269     try {
270       con = getPooledCon();
271       // should be a preparedStatement because is faster
272       stmt = con.createStatement();
273       ResultSet rs = executeSql(stmt,sql);
274     }
275     catch (Exception e) {
276       logger.error("-- delete topics failed ");
277     }
278     finally {
279       freeConnection(con,stmt);
280     }
281   }
282
283
284   public EntityList getContent(EntityTopics topic)
285     throws StorageObjectFailure {
286     EntityList returnList=null;
287     if (topic != null) {
288       String id = topic.getId();
289       String select = "select content_id from " + theTable + " where topic_id=" + id;
290
291       // execute select statement
292       Connection con=null;Statement stmt=null;
293       try {
294         con = getPooledCon();
295         // should be a preparedStatement because is faster
296         stmt = con.createStatement();
297         ResultSet rs = executeSql(stmt,select);
298         if (rs!=null) {
299           String topicSelect= "id IN (";
300           boolean first=true;
301           while (rs.next()) {
302             if (first==false) topicSelect+=",";
303             topicSelect += rs.getString(1);
304             first=false;
305           }
306           topicSelect+=")";
307           if (first==false)
308             returnList = DatabaseContent.getInstance().selectByWhereClause(topicSelect,-1);
309         }
310       }
311       catch (Exception e) {
312         logger.error("-- get contetn failed");
313       }
314       finally { freeConnection(con,stmt);}
315     }
316     return returnList;
317   }
318 }