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