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