some code cleanup. removed unnecessary semikolons, unused vars, etc.
[mir.git] / source / mircoders / storage / DatabaseContentToTopics.java
index 3dc3116..d3f5571 100755 (executable)
-/*\r
- * Copyright (C) 2001, 2002  The Mir-coders group\r
- *\r
- * This file is part of Mir.\r
- *\r
- * Mir is free software; you can redistribute it and/or modify\r
- * it under the terms of the GNU General Public License as published by\r
- * the Free Software Foundation; either version 2 of the License, or\r
- * (at your option) any later version.\r
- *\r
- * Mir is distributed in the hope that it will be useful,\r
- * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
- * GNU General Public License for more details.\r
- *\r
- * You should have received a copy of the GNU General Public License\r
- * along with Mir; if not, write to the Free Software\r
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
- *\r
- * In addition, as a special exception, The Mir-coders gives permission to link\r
- * the code of this program with the com.oreilly.servlet library, any library\r
- * licensed under the Apache Software License, The Sun (tm) Java Advanced\r
- * Imaging library (JAI), The Sun JIMI library (or with modified versions of\r
- * the above that use the same license as the above), and distribute linked\r
- * combinations including the two.  You must obey the GNU General Public\r
- * License in all respects for all of the code used other than the above\r
- * mentioned libraries.  If you modify this file, you may extend this exception\r
- * to your version of the file, but you are not obligated to do so.  If you do\r
- * not wish to do so, delete this exception statement from your version.\r
- */\r
-\r
-package mircoders.storage;\r
-\r
-import java.sql.Connection;\r
-import java.sql.ResultSet;\r
-import java.sql.Statement;\r
-import java.util.ArrayList;\r
-import java.util.Collection;\r
-import java.util.Iterator;\r
-\r
-import mir.entity.EntityList;\r
-import mir.log.LoggerWrapper;\r
-import mir.storage.Database;\r
-import mir.storage.StorageObject;\r
-import mir.storage.StorageObjectFailure;\r
-import mircoders.entity.EntityContent;\r
-import mircoders.entity.EntityTopics;\r
-\r
-/**\r
- * <b>This class implements the 1-n-relation between\r
- * content and topic\r
- *\r
- */\r
-\r
-public class DatabaseContentToTopics extends Database implements StorageObject{\r
-\r
-  private static DatabaseContentToTopics instance;\r
-\r
-  public static DatabaseContentToTopics getInstance() {\r
-    if (instance == null) {\r
-      synchronized (DatabaseContentToTopics.class) {\r
-        if (instance == null) {\r
-          instance = new DatabaseContentToTopics();\r
-          instance.myselfDatabase = instance;\r
-        }\r
-      }\r
-    }\r
-    return instance;\r
-  }\r
-\r
-  private DatabaseContentToTopics() {\r
-    super();\r
-\r
-    logger = new LoggerWrapper("Database.ContentToTopics");\r
-\r
-    hasTimestamp = false;\r
-    theTable="content_x_topic";\r
-    theEntityClass = mir.entity.GenericEntity.class;\r
-  }\r
-\r
-  /**\r
-   * This class return an EntityList of Topics\r
-   * @param EntityContent content\r
-   * @returns EntityList\r
-   */\r
-  public EntityList getTopics(EntityContent content) {\r
-    EntityList returnList=null;\r
-    if (content != null) {\r
-      // get all to_topic from content_x_topic\r
-      String id = content.getId();\r
-      String subselect = "id in (select topic_id from " + theTable + " where content_id=" + id+")";\r
-\r
-      try {\r
-        returnList = DatabaseTopics.getInstance().selectByWhereClause(subselect,-1);\r
-      }\r
-      catch (Exception e) {\r
-        logger.error("-- get topics failed " + e.toString());\r
-      }\r
-    }\r
-    return returnList;\r
-  }\r
-\r
-  /**\r
-   * Returns a ArrayList of Integer-Objects from a content-id.\r
-   * @returns ArrayList\r
-   */\r
-  public ArrayList getTopicsOfContent(String contentId)\r
-    throws StorageObjectFailure {\r
-    ArrayList returnList = new ArrayList();\r
-\r
-    if (contentId != null) {\r
-      String sql = "select topic_id from " + theTable + " where content_id=" + contentId;\r
-      Connection con=null;Statement stmt=null;\r
-      try {\r
-        con = getPooledCon();\r
-        // should be a preparedStatement because is faster\r
-        stmt = con.createStatement();\r
-        ResultSet rs = executeSql(stmt,sql);\r
-        if(rs!=null){\r
-          while(rs.next()){\r
-            returnList.add(new Integer(rs.getInt("topic_id")));\r
-          }\r
-        }\r
-      }\r
-      catch (Exception e) {\r
-        logger.error("DatabaseContentToTopics.getTopicsOfContent: " + e.getMessage());\r
-      }\r
-      finally {\r
-        freeConnection(con,stmt);\r
-      }\r
-    }\r
-    return returnList;\r
-  }\r
-\r
-  /**\r
-   * Set new topics\r
-   */\r
-  public void setTopics(String contentId, String[] topicId)\r
-    throws StorageObjectFailure {\r
-    if (contentId == null){\r
-      return;\r
-    }\r
-    if (topicId==null || topicId[0]==null) {\r
-      return;\r
-    }\r
-    //first check which topics this article has\r
-    Collection hasTopics = getTopicsOfContent(contentId);\r
-    Collection toSet = new ArrayList();\r
-    Collection toDelete = new ArrayList();\r
-\r
-    if(hasTopics!=null && hasTopics.size()>0){\r
-      //now we check if there are new topics and copy them to an array.\r
-      for(int i = 0; i< topicId.length;i++){\r
-        boolean set=false;\r
-        int whichTopic = 0;\r
-        for(Iterator it=hasTopics.iterator();it.hasNext();){\r
-          Integer topic = (Integer)it.next();\r
-          if(topicId[i].equals(topic.toString())){\r
-            set=true;\r
-          } else {\r
-            whichTopic = i;\r
-          }\r
-        }\r
-        if(set==false){\r
-          toSet.add(topicId[i]);\r
-          logger.debug("to set: "+ topicId[i]);\r
-        }\r
-      }\r
-      //now we check if we have to delete topics\r
-      for(Iterator it=hasTopics.iterator();it.hasNext();){\r
-        boolean delete=true;\r
-        int whichTopic = 0;\r
-        Integer topic = (Integer)it.next();\r
-        for(int i = 0; i< topicId.length;i++){\r
-          if(topicId[i].equals(topic.toString())){\r
-            delete=false;\r
-          } else {\r
-            whichTopic = i;\r
-          }\r
-        }\r
-        if(delete==true){\r
-          toDelete.add(topic.toString());\r
-          logger.debug("to delete: "+ topic.toString());\r
-        }\r
-      }\r
-    } else {\r
-      //all the topics has to be set, so we copy all to the array\r
-                        for (int i = 0; i < topicId.length; i++){\r
-                                toSet.add(topicId[i]);\r
-                        }\r
-    }\r
-\r
-    //first delete all row with content_id=contentId\r
-    String sql = "delete from "+ theTable +" where content_id=" + contentId\r
-                + " and topic_id in (";\r
-    boolean first=false;\r
-    for(Iterator it = toDelete.iterator(); it.hasNext();){\r
-      if(first==false){\r
-        first=true;\r
-      } else {\r
-        sql+=",";\r
-      }\r
-      sql+= (String)it.next();\r
-    }\r
-    sql+=")";\r
-    Connection con=null;Statement stmt=null;\r
-    try {\r
-      con = getPooledCon();\r
-      // should be a preparedStatement because is faster\r
-      stmt = con.createStatement();\r
-      int rs = executeUpdate(stmt,sql);\r
-    } catch (Exception e) {\r
-      logger.error("-- deleting topics failed");\r
-    } finally {\r
-      freeConnection(con,stmt);\r
-    }\r
-\r
-    //now insert\r
-    //first delete all row with content_id=contentId\r
-    for (Iterator it = toSet.iterator(); it.hasNext();) {\r
-      sql = "insert into "+ theTable +" (content_id,topic_id) values ("\r
-            + contentId + "," + (String)it.next() + ")";\r
-      try {\r
-        con = getPooledCon();\r
-        // should be a preparedStatement because is faster\r
-        stmt = con.createStatement();\r
-        int rs = executeUpdate(stmt,sql);\r
-      }\r
-      catch (Exception e) {\r
-        logger.error("-- set topics failed -- insert laenge topicId" + topicId.length);\r
-      } finally {\r
-        freeConnection(con,stmt);\r
-      }\r
-    }\r
-  }\r
-\r
-  public void deleteByContentId(String contentId)\r
-    throws StorageObjectFailure {\r
-    if (contentId == null) {\r
-      //theLog.printDebugInfo("-- delete topics failed -- no content id");\r
-      return;\r
-    }\r
-    //delete all row with content_id=contentId\r
-    String sql = "delete from "+ theTable +" where content_id=" + contentId;\r
-\r
-    Connection con=null;Statement stmt=null;\r
-    try {\r
-      con = getPooledCon();\r
-      // should be a preparedStatement because is faster\r
-      stmt = con.createStatement();\r
-      ResultSet rs = executeSql(stmt,sql);\r
-    } catch (Exception e) {\r
-      //theLog.printDebugInfo("-- delete topics failed  ");\r
-    } finally {\r
-      freeConnection(con,stmt);\r
-    }\r
-  }\r
-\r
-  public void deleteByTopicId(String topicId)\r
-    throws StorageObjectFailure {\r
-    if (topicId == null) {\r
-      //theLog.printDebugInfo("-- delete topics failed -- no topic id");\r
-      return;\r
-    }\r
-    //delete all row with content_id=contentId\r
-    String sql = "delete from "+ theTable +" where topic_id=" + topicId;\r
-\r
-    Connection con=null;Statement stmt=null;\r
-    try {\r
-      con = getPooledCon();\r
-      // should be a preparedStatement because is faster\r
-      stmt = con.createStatement();\r
-      ResultSet rs = executeSql(stmt,sql);\r
-    }\r
-    catch (Exception e) {\r
-      logger.error("-- delete topics failed ");\r
-    }\r
-    finally {\r
-      freeConnection(con,stmt);\r
-    }\r
-  }\r
-\r
-\r
-  public EntityList getContent(EntityTopics topic)\r
-    throws StorageObjectFailure {\r
-    EntityList returnList=null;\r
-    if (topic != null) {\r
-      String id = topic.getId();\r
-      String select = "select content_id from " + theTable + " where topic_id=" + id;\r
-\r
-      // execute select statement\r
-      Connection con=null;Statement stmt=null;\r
-      try {\r
-        con = getPooledCon();\r
-        // should be a preparedStatement because is faster\r
-        stmt = con.createStatement();\r
-        ResultSet rs = executeSql(stmt,select);\r
-        if (rs!=null) {\r
-          String topicSelect= "id IN (";\r
-          boolean first=true;\r
-          while (rs.next()) {\r
-            if (first==false) topicSelect+=",";\r
-            topicSelect += rs.getString(1);\r
-            first=false;\r
-          }\r
-          topicSelect+=")";\r
-          if (first==false)\r
-            returnList = DatabaseContent.getInstance().selectByWhereClause(topicSelect,-1);\r
-        }\r
-      }\r
-      catch (Exception e) {\r
-        logger.error("-- get contetn failed");\r
-      }\r
-      finally { freeConnection(con,stmt);}\r
-    }\r
-    return returnList;\r
-  }\r
-}\r
+/*
+ * Copyright (C) 2001, 2002 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
+ */
+
+package mircoders.storage;
+
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
+
+import mir.entity.EntityList;
+import mir.log.LoggerWrapper;
+import mir.storage.Database;
+import mir.storage.StorageObjectFailure;
+import mircoders.entity.EntityContent;
+import mircoders.entity.EntityTopics;
+
+/**
+ * <b>This class implements the 1-n-relation between
+ * content and topic
+ *
+ */
+
+public class DatabaseContentToTopics extends Database {
+
+  private static DatabaseContentToTopics instance;
+
+  public synchronized static DatabaseContentToTopics getInstance() {
+    if (instance == null) {
+      instance = new DatabaseContentToTopics();
+    }
+    return instance;
+  }
+
+  private DatabaseContentToTopics() {
+    super();
+
+    logger = new LoggerWrapper("Database.ContentToTopics");
+    mainTable="content_x_topic";
+    entityClass = mir.entity.GenericEntity.class;
+  }
+
+  /**
+   * This class return an EntityList of Topics
+   */
+  public EntityList getTopics(EntityContent content) {
+    EntityList returnList=null;
+    if (content != null) {
+
+      String id = content.getId();
+      try {
+        ArrayList extraTables = new ArrayList();
+        extraTables.add(mainTable+" cxt");
+        returnList = DatabaseTopics.getInstance()
+                      .selectByWhereClauseWithExtraTables("t",extraTables,
+                                              "t.id=cxt.topic_id and  cxt.content_id="+id );
+      }
+      catch (Exception e) {
+        logger.error("-- get topics failed " + e.toString());
+      }
+    }
+    return returnList;
+  }
+
+  /**
+   * Returns a List of String-Objects from a content-id.
+   */
+  public List getTopicsOfContent(String contentId)
+    throws StorageObjectFailure {
+    ArrayList returnList = new ArrayList();
+
+    if (contentId != null) {
+      String sql = "select topic_id from " + mainTable + " where content_id=" + contentId;
+      Connection con=null;Statement stmt=null;
+      try {
+        con = obtainConnection();
+
+        // should be a preparedStatement because is faster
+        stmt = con.createStatement();
+        ResultSet rs = executeSql(stmt,sql);
+        if(rs!=null){
+          while(rs.next()){
+            returnList.add(Integer.toString(rs.getInt("topic_id")));
+          }
+        }
+      }
+      catch (Exception e) {
+        logger.error("DatabaseContentToTopics.getTopicsOfContent: " + e.getMessage());
+      }
+      finally {
+        freeConnection(con,stmt);
+      }
+    }
+    return returnList;
+  }
+
+  private String getIdListExpression(List aList) {
+    String result = "";
+
+    Iterator i = aList.iterator();
+
+    while (i.hasNext()) {
+      result = result + i.next().toString();
+      if (i.hasNext())
+        result = result + ", ";
+    }
+    return result;
+  }
+
+  public void setTopics(String anArticleId, String [] aTopics) throws StorageObjectFailure {
+    if (aTopics==null)
+      setTopics(anArticleId, (List) null);
+    else
+      setTopics(anArticleId, Arrays.asList(aTopics));
+  }
+
+  public void setTopics(String anArticleId, List aTopics) throws StorageObjectFailure {
+    List newTopics = new ArrayList();
+    if (aTopics!=null) {
+      Iterator i = aTopics.iterator();
+
+      while (i.hasNext()) {
+        newTopics.add(new Integer(Integer.parseInt((String) i.next())));
+      }
+    }
+
+    List currentTopics = getTopicsOfContent(anArticleId);
+    logger.debug("New topics = " + newTopics.toString());
+    logger.debug("Current topics = " + currentTopics.toString());
+    List topicsToDelete = new ArrayList(currentTopics);
+    topicsToDelete.removeAll(newTopics);
+    List topicsToAdd = new ArrayList(newTopics);
+    topicsToAdd.removeAll(currentTopics);
+    logger.debug("to delete = " + topicsToDelete.toString());
+    logger.debug("to add = " + topicsToAdd.toString());
+
+
+    if (!topicsToDelete.isEmpty()) {
+      String sql =
+          "delete from " + mainTable + " " +
+          "where content_id=" + anArticleId +
+          "        and topic_id in (" + getIdListExpression(topicsToDelete) + ")";
+
+      Connection connection=null;
+      Statement statement=null;
+      try {
+        connection = obtainConnection();
+        statement = connection.createStatement();
+        executeUpdate(statement, sql);
+      }
+      catch (Exception e) {
+        logger.error("-- deleting topics failed");
+      }
+      finally {
+        try {
+          freeConnection(connection, statement);
+        }
+        catch (Throwable t) {
+        }
+      }
+    }
+
+    Iterator i = topicsToAdd.iterator();
+    while (i.hasNext()) {
+      Integer topicId = (Integer) i.next();
+      String sql =
+          "insert into " + mainTable + " (content_id, topic_id) "+
+          "values (" + anArticleId + "," + topicId + ")";
+      Connection connection=null;
+      Statement statement=null;
+      try {
+        connection = obtainConnection();
+        // should be a preparedStatement because is faster
+        statement = connection.createStatement();
+        executeUpdate(statement, sql);
+      }
+      catch (Exception e) {
+        logger.error("-- adding topics failed");
+      }
+      finally {
+        try {
+          freeConnection(connection, statement);
+        }
+        catch (Throwable t) {
+        }
+      }
+    }
+  }
+
+  public void deleteByContentId(String contentId)
+    throws StorageObjectFailure {
+    if (contentId == null) {
+      //theLog.printDebugInfo("-- delete topics failed -- no content id");
+      return;
+    }
+    //delete all row with content_id=contentId
+    String sql = "delete from "+ mainTable +" where content_id=" + contentId;
+
+    Connection con=null;Statement stmt=null;
+    try {
+      con = obtainConnection();
+      // should be a preparedStatement because is faster
+      stmt = con.createStatement();
+      executeSql(stmt,sql);
+    } catch (Exception e) {
+      //theLog.printDebugInfo("-- delete topics failed  ");
+    } finally {
+      freeConnection(con,stmt);
+    }
+  }
+
+  public void deleteByTopicId(String topicId)
+    throws StorageObjectFailure {
+    if (topicId == null) {
+      //theLog.printDebugInfo("-- delete topics failed -- no topic id");
+      return;
+    }
+    //delete all row with content_id=contentId
+    String sql = "delete from "+ mainTable +" where topic_id=" + topicId;
+
+    Connection con=null;Statement stmt=null;
+    try {
+      con = obtainConnection();
+      // should be a preparedStatement because is faster
+      stmt = con.createStatement();
+      executeSql(stmt,sql);
+    }
+    catch (Exception e) {
+      logger.error("-- delete topics failed ");
+    }
+    finally {
+      freeConnection(con,stmt);
+    }
+  }
+
+/**
+ * Returns list of Content for a specific topic
+ * @param topic
+ * @return EntityList
+ * @throws StorageObjectFailure
+ */
+  public EntityList getContent(EntityTopics topic)
+    throws StorageObjectFailure {
+    EntityList returnList=null;
+    if (topic != null) {
+      String id = topic.getId();
+      try {
+        ArrayList extraTables = new ArrayList();
+        extraTables.add(mainTable+" cxt");
+        returnList = DatabaseContent.getInstance()
+                      .selectByWhereClauseWithExtraTables("c",extraTables,
+                          "c.id=cxt.content_id and cxt.topic_id="+id );
+      }
+      catch (Exception e) {
+        logger.error("-- get content failed");
+      }
+    }
+    return returnList;
+  }
+}