4a696e41a5276dd906347e5c80bd4a95f919825b
[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;\r
34 import java.sql.ResultSet;\r
35 import java.sql.Statement;\r
36 import java.util.ArrayList;\r
37 import java.util.Arrays;\r
38 import java.util.Iterator;\r
39 import java.util.List;\r
40 import java.util.Vector;\r
41 \r
42 import mir.entity.EntityList;\r
43 import mir.log.LoggerWrapper;\r
44 import mir.storage.Database;\r
45 import mir.storage.StorageObject;\r
46 import mir.storage.StorageObjectFailure;\r
47 import mircoders.entity.EntityContent;\r
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       // get all to_topic from content_x_topic
86       String id = content.getId();
87       String subselect = "id in (select topic_id from " + theTable + " where content_id=" + id+")";
88
89       try {
90         returnList = DatabaseTopics.getInstance().selectByWhereClause(subselect,-1);
91       }
92       catch (Exception e) {
93         logger.error("-- get topics failed " + e.toString());
94       }
95     }
96     return returnList;
97   }
98
99   /**
100    * Returns a ArrayList of Integer-Objects from a content-id.
101    * @returns ArrayList
102    */
103   public List getTopicsOfContent(String contentId)
104     throws StorageObjectFailure {
105     ArrayList returnList = new ArrayList();
106
107     if (contentId != null) {
108       String sql = "select topic_id from " + theTable + " where content_id=" + contentId;
109       Connection con=null;Statement stmt=null;
110       try {
111         con = getPooledCon();
112         // should be a preparedStatement because is faster
113         stmt = con.createStatement();
114         ResultSet rs = executeSql(stmt,sql);
115         if(rs!=null){
116           while(rs.next()){
117             returnList.add(new Integer(rs.getInt("topic_id")));
118           }
119         }
120       }
121       catch (Exception e) {
122         logger.error("DatabaseContentToTopics.getTopicsOfContent: " + e.getMessage());
123       }
124       finally {
125         freeConnection(con,stmt);
126       }
127     }
128     return returnList;
129   }
130
131   private String getIdListExpression(List aList) {
132     String result = "";
133
134     Iterator i = aList.iterator();
135
136     while (i.hasNext()) {
137       result = result + i.next().toString();
138       if (i.hasNext())
139         result = result + ", ";
140     }
141     return result;
142   }
143
144   public void setTopics(String anArticleId, String [] aTopics) throws StorageObjectFailure {
145     if (aTopics==null)
146       setTopics(anArticleId, (List) null);
147     else
148       setTopics(anArticleId, Arrays.asList(aTopics));
149   }
150
151   public void setTopics(String anArticleId, List aTopics) throws StorageObjectFailure {
152     List newTopics = new Vector();
153     if (aTopics!=null) {
154       Iterator i = aTopics.iterator();
155
156       while (i.hasNext()) {
157         newTopics.add(new Integer(Integer.parseInt((String) i.next())));
158       }
159     }
160
161     List currentTopics = getTopicsOfContent(anArticleId);
162     logger.debug("New topics = " + newTopics.toString());
163     logger.debug("Current topics = " + currentTopics.toString());
164     List topicsToDelete = new Vector(currentTopics);
165     topicsToDelete.removeAll(newTopics);
166     List topicsToAdd = new Vector(newTopics);
167     topicsToAdd.removeAll(currentTopics);
168     logger.debug("to delete = " + topicsToDelete.toString());
169     logger.debug("to add = " + topicsToAdd.toString());
170
171
172     if (!topicsToDelete.isEmpty()) {
173       String sql =
174           "delete from " + theTable + " " +
175           "where content_id=" + anArticleId +
176           "        and topic_id in (" + getIdListExpression(topicsToDelete) + ")";
177
178       Connection connection=null;
179       Statement statement=null;
180       try {
181         connection = getPooledCon();
182         statement = connection.createStatement();
183         int rs = executeUpdate(statement, sql);
184       }
185       catch (Exception e) {
186         logger.error("-- deleting topics failed");
187       }
188       finally {
189         try {
190           freeConnection(connection, statement);
191         }
192         catch (Throwable t) {
193         }
194       }
195     }
196
197     Iterator i = topicsToAdd.iterator();
198     while (i.hasNext()) {
199       Integer topicId = (Integer) i.next();
200       String sql =
201           "insert into " + theTable + " (content_id, topic_id) "+
202           "values (" + anArticleId + "," + topicId + ")";
203       Connection connection=null;
204       Statement statement=null;
205       try {
206         connection = getPooledCon();
207         // should be a preparedStatement because is faster
208         statement = connection.createStatement();
209         int rs = executeUpdate(statement, sql);
210       }
211       catch (Exception e) {
212         logger.error("-- adding topics failed");
213       }
214       finally {
215         try {
216           freeConnection(connection, statement);
217         }
218         catch (Throwable t) {
219         }
220       }
221     }
222   }
223
224   public void deleteByContentId(String contentId)
225     throws StorageObjectFailure {
226     if (contentId == null) {
227       //theLog.printDebugInfo("-- delete topics failed -- no content id");
228       return;
229     }
230     //delete all row with content_id=contentId
231     String sql = "delete from "+ theTable +" where content_id=" + contentId;
232
233     Connection con=null;Statement stmt=null;
234     try {
235       con = getPooledCon();
236       // should be a preparedStatement because is faster
237       stmt = con.createStatement();
238       ResultSet rs = executeSql(stmt,sql);
239     } catch (Exception e) {
240       //theLog.printDebugInfo("-- delete topics failed  ");
241     } finally {
242       freeConnection(con,stmt);
243     }
244   }
245
246   public void deleteByTopicId(String topicId)
247     throws StorageObjectFailure {
248     if (topicId == null) {
249       //theLog.printDebugInfo("-- delete topics failed -- no topic id");
250       return;
251     }
252     //delete all row with content_id=contentId
253     String sql = "delete from "+ theTable +" where topic_id=" + topicId;
254
255     Connection con=null;Statement stmt=null;
256     try {
257       con = getPooledCon();
258       // should be a preparedStatement because is faster
259       stmt = con.createStatement();
260       ResultSet rs = executeSql(stmt,sql);
261     }
262     catch (Exception e) {
263       logger.error("-- delete topics failed ");
264     }
265     finally {
266       freeConnection(con,stmt);
267     }
268   }
269
270
271   public EntityList getContent(EntityTopics topic)
272     throws StorageObjectFailure {
273     EntityList returnList=null;
274     if (topic != null) {
275       String id = topic.getId();
276       String select = "select content_id from " + theTable + " where topic_id=" + id;
277
278       // execute select statement
279       Connection con=null;Statement stmt=null;
280       try {
281         con = getPooledCon();
282         // should be a preparedStatement because is faster
283         stmt = con.createStatement();
284         ResultSet rs = executeSql(stmt,select);
285         if (rs!=null) {
286           String topicSelect= "id IN (";
287           boolean first=true;
288           while (rs.next()) {
289             if (first==false) topicSelect+=",";
290             topicSelect += rs.getString(1);
291             first=false;
292           }
293           topicSelect+=")";
294           if (first==false)
295             returnList = DatabaseContent.getInstance().selectByWhereClause(topicSelect,-1);
296         }
297       }
298       catch (Exception e) {
299         logger.error("-- get contetn failed");
300       }
301       finally { freeConnection(con,stmt);}
302     }
303     return returnList;
304   }
305 }