1.1 restoration
[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     mainTable="content_x_topic";
74     theEntityClass = mir.entity.GenericEntity.class;
75   }
76
77   /**
78    * This class return an EntityList of Topics
79    */
80   public EntityList getTopics(EntityContent content) {
81     EntityList returnList=null;
82     if (content != null) {
83
84       String id = content.getId();
85       try {
86         Vector extraTables = new Vector();
87         extraTables.add(mainTable+" cxt");
88         returnList = DatabaseTopics.getInstance()
89                        .selectByWhereClauseWithExtraTables("t",extraTables,
90                                                "t.id=cxt.topic_id and  cxt.content_id="+id );
91       }
92       catch (Exception e) {
93         logger.error("-- get topics failed " + e.toString());
94       }
95     }
96     return returnList;
97   }
98
99   /**
100    * Returns a List of String-Objects from a content-id.
101    */
102   public List getTopicsOfContent(String contentId)
103     throws StorageObjectFailure {
104     ArrayList returnList = new ArrayList();
105
106     if (contentId != null) {
107       String sql = "select topic_id from " + mainTable + " where content_id=" + contentId;
108       Connection con=null;Statement stmt=null;
109       try {
110         con = obtainConnection();
111
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(Integer.toString(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 ArrayList(currentTopics);
165     topicsToDelete.removeAll(newTopics);
166     List topicsToAdd = new ArrayList(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 " + mainTable + " " +
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 = obtainConnection();
182         statement = connection.createStatement();
183         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 " + mainTable + " (content_id, topic_id) "+
202           "values (" + anArticleId + "," + topicId + ")";
203       Connection connection=null;
204       Statement statement=null;
205       try {
206         connection = obtainConnection();
207         // should be a preparedStatement because is faster
208         statement = connection.createStatement();
209         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 "+ mainTable +" where content_id=" + contentId;
232
233     Connection con=null;Statement stmt=null;
234     try {
235       con = obtainConnection();
236       // should be a preparedStatement because is faster
237       stmt = con.createStatement();
238       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 "+ mainTable +" where topic_id=" + topicId;
254
255     Connection con=null;Statement stmt=null;
256     try {
257       con = obtainConnection();
258       // should be a preparedStatement because is faster
259       stmt = con.createStatement();
260       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  * Returns list of Content for a specific topic
272  * @param topic
273  * @return EntityList
274  * @throws StorageObjectFailure
275  */
276   public EntityList getContent(EntityTopics topic)
277     throws StorageObjectFailure {
278     EntityList returnList=null;
279     if (topic != null) {
280       String id = topic.getId();
281       try {
282         Vector extraTables = new Vector();
283         extraTables.add(mainTable+" cxt");
284         returnList = DatabaseContent.getInstance()
285                       .selectByWhereClauseWithExtraTables("c",extraTables,
286                           "c.id=cxt.content_id and cxt.topic_id="+id );
287       }
288       catch (Exception e) {
289         logger.error("-- get content failed");
290       }
291     }
292     return returnList;
293   }
294 }