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