From 95c2e3a74f492f6f61d4dbe8bb47996f43af0627 Mon Sep 17 00:00:00 2001 From: zapata Date: Sat, 26 Mar 2005 11:26:23 +0000 Subject: [PATCH] some db code rewriting fixed a bug concerning editing and saving media --- source/Mir.java | 49 +- source/mir/entity/AbstractEntity.java | 23 +- source/mir/entity/Entity.java | 22 +- source/mir/entity/EntityBrowser.java | 11 +- source/mir/entity/EntityList.java | 2 +- source/mir/entity/adapter/EntityAdapter.java | 5 +- source/mir/entity/adapter/EntityAdapterEngine.java | 23 +- .../mir/entity/adapter/EntityIteratorAdapter.java | 8 +- source/mir/generator/GeneratorHelper.java | 22 +- source/mir/media/MediaHandler.java | 8 +- source/mir/media/image/ImageProcessor.java | 84 +++ .../media/image/JAIImageProcessor.java} | 440 ++++++----- source/mir/module/AbstractModule.java | 31 +- source/mir/servlet/AbstractServlet.java | 51 +- source/mir/servlet/ServletModule.java | 2 +- source/mir/servlet/ServletModuleDispatch.java | 12 +- source/mir/storage/Database.java | 817 +++++++-------------- .../{StorageObjectExc.java => DatabaseExc.java} | 14 +- ...rageObjectFailure.java => DatabaseFailure.java} | 12 +- source/mir/storage/RecordInserter.java | 114 +++ source/mir/storage/RecordRetriever.java | 148 ++++ source/mir/storage/RecordUpdater.java | 96 +++ source/mir/storage/StatementGenerator.java | 149 ++++ source/mir/util/xml/html/HTMLScanner.java | 1 + source/mircoders/abuse/FilterEngine.java | 21 +- source/mircoders/entity/EntityComment.java | 18 +- source/mircoders/entity/EntityContent.java | 16 +- source/mircoders/entity/EntityImages.java | 26 +- source/mircoders/entity/EntityUploadedMedia.java | 14 +- .../basic/MirBasicAdminInterfaceLocalizer.java | 36 +- source/mircoders/media/MediaHandlerImages.java | 23 +- .../mircoders/media/MediaHandlerImagesExtern.java | 4 +- source/mircoders/module/ModuleComment.java | 8 - source/mircoders/module/ModuleLanguage.java | 9 - source/mircoders/module/ModuleMediaType.java | 23 +- source/mircoders/module/ModuleUsers.java | 14 +- source/mircoders/search/AudioSearchTerm.java | 4 +- source/mircoders/search/ImagesSearchTerm.java | 4 +- source/mircoders/search/MediaSearchTerm.java | 4 +- source/mircoders/search/TopicMatrixSearchTerm.java | 4 +- source/mircoders/search/TopicSearchTerm.java | 4 +- source/mircoders/search/VideoSearchTerm.java | 4 +- source/mircoders/servlet/ServletModuleAbuse.java | 6 +- source/mircoders/servlet/ServletModuleAdmin.java | 38 +- source/mircoders/servlet/ServletModuleComment.java | 31 +- source/mircoders/servlet/ServletModuleContent.java | 14 +- source/mircoders/servlet/ServletModuleHidden.java | 36 +- .../mircoders/servlet/ServletModuleOpenIndy.java | 6 +- .../servlet/ServletModuleUploadedMedia.java | 73 +- source/mircoders/servlet/ServletModuleUsers.java | 34 +- source/mircoders/storage/DatabaseArticleType.java | 15 +- source/mircoders/storage/DatabaseAudio.java | 13 +- source/mircoders/storage/DatabaseBreaking.java | 12 +- source/mircoders/storage/DatabaseComment.java | 13 +- .../mircoders/storage/DatabaseCommentStatus.java | 6 +- .../mircoders/storage/DatabaseCommentToMedia.java | 40 +- source/mircoders/storage/DatabaseContent.java | 35 +- .../mircoders/storage/DatabaseContentToMedia.java | 34 +- .../mircoders/storage/DatabaseContentToTopics.java | 28 +- source/mircoders/storage/DatabaseFilter.java | 4 - source/mircoders/storage/DatabaseFilterGroup.java | 4 - source/mircoders/storage/DatabaseImageColor.java | 6 - source/mircoders/storage/DatabaseImageFormat.java | 6 - source/mircoders/storage/DatabaseImageLayout.java | 6 - source/mircoders/storage/DatabaseImageType.java | 10 - source/mircoders/storage/DatabaseImages.java | 19 +- source/mircoders/storage/DatabaseLanguage.java | 8 +- source/mircoders/storage/DatabaseMediaType.java | 11 +- source/mircoders/storage/DatabaseMessages.java | 11 - source/mircoders/storage/DatabaseOther.java | 25 +- source/mircoders/storage/DatabaseRights.java | 14 +- source/mircoders/storage/DatabaseTopics.java | 16 +- .../mircoders/storage/DatabaseUploadedMedia.java | 10 +- source/mircoders/storage/DatabaseUsers.java | 17 +- source/mircoders/storage/DatabaseVideo.java | 20 +- 75 files changed, 1473 insertions(+), 1528 deletions(-) create mode 100755 source/mir/media/image/ImageProcessor.java rename source/{mircoders/media/ImageProcessor.java => mir/media/image/JAIImageProcessor.java} (76%) rename source/mir/storage/{StorageObjectExc.java => DatabaseExc.java} (88%) rename source/mir/storage/{StorageObjectFailure.java => DatabaseFailure.java} (88%) create mode 100755 source/mir/storage/RecordInserter.java create mode 100755 source/mir/storage/RecordRetriever.java create mode 100755 source/mir/storage/RecordUpdater.java create mode 100755 source/mir/storage/StatementGenerator.java diff --git a/source/Mir.java b/source/Mir.java index 8d291125..f3a0b79d 100755 --- a/source/Mir.java +++ b/source/Mir.java @@ -28,48 +28,29 @@ * If you do not wish to do so, delete this exception statement from your version. */ -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Map; +import mir.bundle.Bundle; +import mir.config.MirPropertiesConfiguration; +import mir.log.LoggerWrapper; +import mir.servlet.*; +import mir.util.StringRoutines; +import mir.util.ExceptionFunctions; +import multex.Failure; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.UnavailableException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import javax.servlet.http.HttpSessionBindingEvent; -import javax.servlet.http.HttpSessionBindingListener; +import javax.servlet.http.*; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.lang.reflect.Method; +import java.util.*; -import mir.bundle.Bundle; -import mir.config.MirPropertiesConfiguration; -import mir.log.LoggerWrapper; -import mir.servlet.AbstractServlet; -import mir.servlet.ServletModule; -import mir.servlet.ServletModuleDispatch; -import mir.servlet.ServletModuleExc; -import mir.servlet.ServletModuleUserExc; -import mir.util.ExceptionFunctions; -import mir.util.StringRoutines; -import mircoders.entity.EntityUsers; -import mircoders.global.MirGlobal; import mircoders.module.ModuleUsers; +import mircoders.global.MirGlobal; import mircoders.servlet.ServletHelper; -import multex.Failure; +import mircoders.entity.EntityUsers; -/** - * Mir.java - main servlet, that dispatches to servletmodules - */ public class Mir extends AbstractServlet { private static ModuleUsers usersModule = null; private final static Map servletModuleInstanceHash = new HashMap(); diff --git a/source/mir/entity/AbstractEntity.java b/source/mir/entity/AbstractEntity.java index ee350740..a56572ed 100755 --- a/source/mir/entity/AbstractEntity.java +++ b/source/mir/entity/AbstractEntity.java @@ -36,15 +36,15 @@ import java.util.Map; import mir.config.MirPropertiesConfiguration; import mir.log.LoggerWrapper; +import mir.storage.DatabaseExc; +import mir.storage.DatabaseFailure; import mir.storage.Database; -import mir.storage.StorageObjectExc; -import mir.storage.StorageObjectFailure; /** * Base class the entities are derived from. Provides base functionality of * an entity. * - * @version $Id: AbstractEntity.java,v 1.8.2.6 2005/02/10 16:22:30 rhindes Exp $ + * @version $Id: AbstractEntity.java,v 1.8.2.7 2005/03/26 11:26:23 zapata Exp $ */ public class AbstractEntity implements Entity { @@ -89,17 +89,18 @@ public class AbstractEntity implements Entity { } /** {@inheritDoc} */ - public String insert() throws StorageObjectExc { + public String insert() throws DatabaseExc { logger.debug("Entity: trying to insert ..."); if (database != null) { return database.insert(this); } - throw new StorageObjectExc("database == null!"); + + throw new DatabaseExc("database == null!"); } /** {@inheritDoc} */ - public void update() throws StorageObjectFailure { + public void update() throws DatabaseFailure { database.update(this); } @@ -123,9 +124,9 @@ public class AbstractEntity implements Entity { * supplied was not found in the Entity. * @param theProp The field name whose value has to be set * @param theValue The new value of the field - * @exception StorageObjectFailure + * @exception DatabaseFailure */ - public void setFieldValue(String theProp, String theValue) throws StorageObjectFailure { + public void setFieldValue(String theProp, String theValue) throws DatabaseFailure { if (hasField(theProp)) values.put(theProp, theValue); else { @@ -136,16 +137,16 @@ public class AbstractEntity implements Entity { /** * Returns the field names of the Entity */ - public List getFieldNames() throws StorageObjectFailure { + public List getFieldNames() throws DatabaseFailure { return database.getFieldNames(); } /** Returns whether fieldName is a valid field name of this Entity. * @param fieldName * @return true in case fieldName is a field name, else false. - * @exception StorageObjectFailure + * @exception DatabaseFailure */ - public boolean hasField(String fieldName) throws StorageObjectFailure { + public boolean hasField(String fieldName) throws DatabaseFailure { return getFieldNames().contains(fieldName); } } diff --git a/source/mir/entity/Entity.java b/source/mir/entity/Entity.java index df2cb9a4..eb4b8b1b 100755 --- a/source/mir/entity/Entity.java +++ b/source/mir/entity/Entity.java @@ -29,17 +29,17 @@ */ package mir.entity; -import java.util.List; import java.util.Map; +import java.util.List; -import mir.storage.StorageObjectExc; -import mir.storage.StorageObjectFailure; +import mir.storage.DatabaseExc; +import mir.storage.DatabaseFailure; /** * An Entity represents a persistent data object, typically * stored in a database.

* - * @version $Id: Entity.java,v 1.21.2.11 2005/02/10 16:22:30 rhindes Exp $ + * @version $Id: Entity.java,v 1.21.2.12 2005/03/26 11:26:23 zapata Exp $ */ public interface Entity { @@ -66,29 +66,29 @@ public interface Entity { /** * Insers Entity into the database via Database * @return Primary Key of the Entity - * @exception StorageObjectExc + * @exception DatabaseExc */ - public String insert() throws StorageObjectExc; + public String insert() throws DatabaseExc; /** * Saves changes of this Entity to the database - * @exception StorageObjectFailure + * @exception DatabaseFailure */ - public void update() throws StorageObjectFailure; + public void update() throws DatabaseFailure; /** * Sets the value for a field. Issues a log message if the field name * supplied was not found in the Entity. * @param theProp The field name whose value has to be set * @param theValue The new value of the field - * @exception StorageObjectFailure + * @exception DatabaseFailure */ public void setFieldValue(String theProp, String theValue); /** * Returns the field names of the Entity */ - public List getFieldNames() throws StorageObjectFailure; + public List getFieldNames() throws DatabaseFailure; /** * Returns the value of a field by field name. @@ -101,6 +101,6 @@ public interface Entity { /** Returns whether fieldName is a valid field name of this Entity. */ - public boolean hasField(String aFieldName) throws StorageObjectFailure; + public boolean hasField(String aFieldName) throws DatabaseFailure; } diff --git a/source/mir/entity/EntityBrowser.java b/source/mir/entity/EntityBrowser.java index 7d42057f..51b07f61 100755 --- a/source/mir/entity/EntityBrowser.java +++ b/source/mir/entity/EntityBrowser.java @@ -33,7 +33,8 @@ package mir.entity; import java.util.List; import mir.storage.Database; -import mir.storage.StorageObjectFailure; +import mir.storage.DatabaseFailure; +import mir.storage.DatabaseExc; import mir.util.RewindableIterator; import multex.Failure; @@ -55,7 +56,7 @@ public class EntityBrowser implements RewindableIterator { public EntityBrowser(Database aDatabase, String aMainTablePrefix, List someExtraTables, String aWhereClause, String anOrderByClause, - int aBatchSize, int aLimit, int aSkip) throws StorageObjectFailure { + int aBatchSize, int aLimit, int aSkip) throws DatabaseFailure { database=aDatabase; mainTablePrefix=aMainTablePrefix; @@ -70,17 +71,17 @@ public class EntityBrowser implements RewindableIterator { } public EntityBrowser(Database aDatabase, String aWhereClause, String anOrderByClause, - int aBatchSize, int aLimit, int aSkip) throws StorageObjectFailure { + int aBatchSize, int aLimit, int aSkip) throws DatabaseFailure { this(aDatabase, "", null, aWhereClause, anOrderByClause, aBatchSize, aLimit, aSkip); } public EntityBrowser(Database aDatabase, String aWhereClause, String anOrderByClause, - int aBatchSize) throws StorageObjectFailure { + int aBatchSize) throws DatabaseFailure { this(aDatabase, aWhereClause, anOrderByClause, aBatchSize, -1, 0); } - public void readCurrentBatch(int aSkip) throws StorageObjectFailure { + public void readCurrentBatch(int aSkip) throws DatabaseExc, DatabaseFailure { currentBatch = database.selectByWhereClause(mainTablePrefix, extraTables, whereClause, orderByClause, aSkip, batchSize); batchPosition = aSkip; diff --git a/source/mir/entity/EntityList.java b/source/mir/entity/EntityList.java index 700d85d8..aae8f662 100755 --- a/source/mir/entity/EntityList.java +++ b/source/mir/entity/EntityList.java @@ -45,7 +45,7 @@ import mir.storage.store.StoreUtil; * Container class for lists of Entities. * Now implements @see mir.database.store.StorableObject. * - * @author + * @author rk * first version 27.6.1999 * * @version 1.1 (cleaned up) diff --git a/source/mir/entity/adapter/EntityAdapter.java b/source/mir/entity/adapter/EntityAdapter.java index 0006328d..4314dc8d 100755 --- a/source/mir/entity/adapter/EntityAdapter.java +++ b/source/mir/entity/adapter/EntityAdapter.java @@ -159,10 +159,7 @@ public class EntityAdapter implements Map { public Object getRelation(String aWhereClause, String anOrderByClause, String aDefinition) { try { - return - new CachingRewindableIterator( - new EntityIteratorAdapter( - aWhereClause, anOrderByClause, -1, getModel(), aDefinition)); + return EntityAdapterEngine.retrieveAdapterList(model, aDefinition, aWhereClause, anOrderByClause, -1, 0); } catch (Throwable t) { throw new RuntimeException(t.getMessage()); diff --git a/source/mir/entity/adapter/EntityAdapterEngine.java b/source/mir/entity/adapter/EntityAdapterEngine.java index 60312882..5e9e38a0 100755 --- a/source/mir/entity/adapter/EntityAdapterEngine.java +++ b/source/mir/entity/adapter/EntityAdapterEngine.java @@ -33,31 +33,12 @@ package mir.entity.adapter; import java.util.List; import mir.entity.EntityBrowser; -import mir.storage.StorageObjectFailure; - -/** - *

Title:

- *

Description:

- *

Copyright: Copyright (c) 2003

- *

Company:

- * @author not attributable - * @version 1.0 - */ +import mir.storage.DatabaseFailure; public class EntityAdapterEngine { private EntityAdapterEngine() { } - /** - * - * @param aModel - * @param aDefinition - * @param aQualifier - * @param anOrder - * @param aLimit - * @param anOffset - * @return - */ static public List retrieveAdapterList(EntityAdapterModel aModel, String aDefinition, String aQualifier, String anOrder, int aLimit, int anOffset) { try { EntityBrowser browser = new EntityBrowser(aModel.getMappingForName(aDefinition).getDatabase(), aQualifier, anOrder, 30, aLimit, anOffset); @@ -65,7 +46,7 @@ public class EntityAdapterEngine { return new EntityListAdapter(aModel, aDefinition, browser, aLimit); } catch (Throwable t) { - throw new StorageObjectFailure(t); + throw new DatabaseFailure(t); } } } \ No newline at end of file diff --git a/source/mir/entity/adapter/EntityIteratorAdapter.java b/source/mir/entity/adapter/EntityIteratorAdapter.java index 967809bb..1990c731 100755 --- a/source/mir/entity/adapter/EntityIteratorAdapter.java +++ b/source/mir/entity/adapter/EntityIteratorAdapter.java @@ -33,7 +33,7 @@ import java.util.List; import mir.entity.Entity; import mir.entity.EntityBrowser; -import mir.storage.StorageObjectFailure; +import mir.storage.DatabaseFailure; import mir.util.RewindableIterator; public class EntityIteratorAdapter implements RewindableIterator { @@ -49,20 +49,20 @@ public class EntityIteratorAdapter implements RewindableIterator { public EntityIteratorAdapter(String aWhereClause, String anOrderByClause, int aBatchSize, EntityAdapterModel aModel, String aDefinitionName ) - throws StorageObjectFailure { + throws DatabaseFailure { this(new EntityBrowser(aModel.getMappingForName(aDefinitionName).getDatabase(), aWhereClause, anOrderByClause, aBatchSize), aModel, aDefinitionName); } public EntityIteratorAdapter(String aWhereClause, String anOrderByClause, int aBatchSize, EntityAdapterModel aModel, String aDefinitionName, - int aLimit, int aSkip) throws StorageObjectFailure { + int aLimit, int aSkip) throws DatabaseFailure { this(new EntityBrowser(aModel.getMappingForName(aDefinitionName).getDatabase(), aWhereClause, anOrderByClause, aBatchSize, aLimit, aSkip), aModel, aDefinitionName); } public EntityIteratorAdapter(String aMainTablePrefix, List someExtraTables, String aWhereClause, String anOrderByClause, int aBatchSize, EntityAdapterModel aModel, String aDefinitionName, - int aLimit, int aSkip) throws StorageObjectFailure { + int aLimit, int aSkip) throws DatabaseFailure { this(new EntityBrowser(aModel.getMappingForName(aDefinitionName).getDatabase(), aMainTablePrefix, someExtraTables, aWhereClause, anOrderByClause, aBatchSize, aLimit, aSkip), aModel, aDefinitionName); } diff --git a/source/mir/generator/GeneratorHelper.java b/source/mir/generator/GeneratorHelper.java index 0e551122..292d8816 100755 --- a/source/mir/generator/GeneratorHelper.java +++ b/source/mir/generator/GeneratorHelper.java @@ -30,18 +30,14 @@ package mir.generator; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - import mir.bundle.Bundle; -import mir.entity.adapter.EntityIteratorAdapter; -import mir.util.CachingRewindableIterator; +import mir.entity.adapter.EntityAdapterEngine; +import mir.entity.adapter.EntityAdapterModel; import mir.util.generator.BundleGeneratorFunction; import mircoders.global.MirGlobal; +import java.util.*; + public class GeneratorHelper { @@ -54,13 +50,15 @@ public class GeneratorHelper { Map result = new HashMap(); MirGlobal.localizer().producerAssistant().initializeGenerationValueSet(result); - Object languages = new CachingRewindableIterator(new EntityIteratorAdapter("", "id", 30, MirGlobal.localizer().dataModel().adapterModel(), "language")); + EntityAdapterModel model = MirGlobal.localizer().dataModel().adapterModel(); + + List languages = EntityAdapterEngine.retrieveAdapterList(model, "language", "", "id", -1, 0); - Object topics = new CachingRewindableIterator(new EntityIteratorAdapter("", "id", 30, MirGlobal.localizer().dataModel().adapterModel(), "topic")); + List topics = EntityAdapterEngine.retrieveAdapterList(model, "topic", "", "id", -1, 0); - Object articleTypes = new CachingRewindableIterator(new EntityIteratorAdapter("", "id", 30, MirGlobal.localizer().dataModel().adapterModel(), "articleType")); + List articleTypes = EntityAdapterEngine.retrieveAdapterList(model, "articleType", "", "id", -1, 0); - Object commentStatuses = new CachingRewindableIterator(new EntityIteratorAdapter("", "id", 30, MirGlobal.localizer().dataModel().adapterModel(), "commentStatus")); + List commentStatuses = EntityAdapterEngine.retrieveAdapterList(model, "commentStatus", "", "id", -1, 0); result.put("commentstatuses", commentStatuses); result.put("articletypes", articleTypes); diff --git a/source/mir/media/MediaHandler.java b/source/mir/media/MediaHandler.java index cc1ea370..a957c45b 100755 --- a/source/mir/media/MediaHandler.java +++ b/source/mir/media/MediaHandler.java @@ -29,12 +29,12 @@ */ package mir.media; -import java.io.File; -import java.io.InputStream; - import mir.entity.Entity; import mir.session.UploadedFile; +import java.io.File; +import java.io.InputStream; + /** * Interface for Media handling in Mir. All media handlers * must implement this interface. Each specific media type, @@ -80,7 +80,7 @@ import mir.session.UploadedFile; * ) and just override the things that need to be specific. see MediaHandlerAudio * * @author , the Mir-coders group - * @version $Id: MediaHandler.java,v 1.1.2.5 2005/01/23 15:36:03 zapata Exp $ + * @version $Id: MediaHandler.java,v 1.1.2.6 2005/03/26 11:26:24 zapata Exp $ */ public interface MediaHandler { diff --git a/source/mir/media/image/ImageProcessor.java b/source/mir/media/image/ImageProcessor.java new file mode 100755 index 00000000..89c72435 --- /dev/null +++ b/source/mir/media/image/ImageProcessor.java @@ -0,0 +1,84 @@ +/* + * 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 mir.media.image; + +import mir.media.MediaExc; + +import java.io.File; +import java.io.IOException; +import java.io.OutputStream; + +public interface ImageProcessor { + public void descaleImage(int aMaxSize) throws MediaExc; + + public void descaleImage(int aMaxSize, float aMinDescale) throws MediaExc; + + public void descaleImage(int aMaxSize, int aMinResize) throws MediaExc; + + public void descaleImage(int aMaxSize, float aMinDescale, int aMinResize) throws MediaExc; + + /** + * Resizes an image to fit inside aMaxWidth and aMaxHeight, provided + * this requires at least aMinResize pixels will be removed from either the width or + * the height + */ + public void descaleImage(int aMaxWidth, int aMaxHeight, float aMinDescale, int aMinResize) throws MediaExc; + + public void scaleImage(float aScalingFactor) throws MediaExc; + + public int getWidth(); + public int getHeight(); + public int getScaledWidth(); + public int getScaledHeight(); + public void writeScaledData(OutputStream aStream, String anImageType); + public byte[] getScaledData(String anImageType); + public void writeScaledData(File aFile, String anImageType) throws MediaExc; +} + + + + + + + + + + + + + + + + + + + + diff --git a/source/mircoders/media/ImageProcessor.java b/source/mir/media/image/JAIImageProcessor.java similarity index 76% rename from source/mircoders/media/ImageProcessor.java rename to source/mir/media/image/JAIImageProcessor.java index 2c7877e9..986a3f30 100755 --- a/source/mircoders/media/ImageProcessor.java +++ b/source/mir/media/image/JAIImageProcessor.java @@ -1,229 +1,211 @@ -/* - * 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.media; - -import java.awt.RenderingHints; -import java.awt.image.ColorModel; -import java.awt.image.DataBuffer; -import java.awt.image.PixelInterleavedSampleModel; -import java.awt.image.RenderedImage; -import java.io.BufferedOutputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -import javax.media.jai.ImageLayout; -import javax.media.jai.InterpolationBilinear; -import javax.media.jai.JAI; -import javax.media.jai.ParameterBlockJAI; - -import mir.log.LoggerWrapper; - -import com.sun.media.jai.codec.ByteArraySeekableStream; -import com.sun.media.jai.codec.FileSeekableStream; -import com.sun.media.jai.codec.SeekableStream; - -/** - * - *

Title: Image processor

- *

Description: Temporary image processor class. (Made for the immediate needs of CMI brasil. - * Will become obsolete when mh's media handler rewrite is finished.

- * @author Zapata - * @version 1.0 - */ - -public class ImageProcessor { - static final LoggerWrapper logger = new LoggerWrapper("media"); - - private RenderedImage image; - private RenderedImage scaledImage; - - public ImageProcessor(RenderedImage anImage) throws IOException { - image = anImage; - scaledImage = anImage; - } - - public ImageProcessor(SeekableStream anImageStream) throws IOException { - RenderedImage tempImage = JAI.create("stream", anImageStream); - ParameterBlockJAI params = new ParameterBlockJAI("format"); - int bands[]; - int nrComponents; - - - params.addSource(tempImage); - params.setParameter("dataType", DataBuffer.TYPE_BYTE); - - ImageLayout layout = new ImageLayout(); - nrComponents = tempImage.getColorModel().getNumColorComponents(); - - bands = new int[nrComponents]; - for (int i=0; iaMaxWidth and aMaxHeight, provided - * this requires at least aMinResize pixels will be removed from either the width or - * the height - * - * @param aMaxWidth - * @param aMaxHeight - * @param aMinDescale - * @param aMinResize - * @throws java.io.IOException - */ - public void descaleImage(int aMaxWidth, int aMaxHeight, float aMinDescale, int aMinResize) throws java.io.IOException { - float scale; - scaledImage = image; - - if ((aMaxWidth>0 && image.getWidth()>aMaxWidth+aMinResize-1) || (aMaxHeight>0 && image.getHeight()>aMaxHeight+aMinResize-1)) - { - logger.info("Scaling image"); - - scale=1; - - if (aMaxWidth>0 && image.getWidth()>aMaxWidth) { - scale = Math.min(scale, (float) aMaxWidth / (float) image.getWidth()); - } - if (aMaxHeight>0 && image.getHeight()>aMaxHeight) { - scale = Math.min(scale, (float) aMaxHeight / (float) image.getHeight()); - } - - if (1-scale>aMinDescale) { - scaleImage(scale); - } - } - } - - public void scaleImage(float aScalingFactor) throws java.io.IOException { - ParameterBlockJAI params = new ParameterBlockJAI("scale"); - params.addSource(image); - - params.setParameter("xScale", aScalingFactor); - params.setParameter("yScale", aScalingFactor); - params.setParameter("xTrans", 0.0F); - params.setParameter("yTrans", 0.0F); - params.setParameter("interpolation", new InterpolationBilinear()); - scaledImage = JAI.create("scale", params); - } - - public int getWidth() { - return image.getWidth(); - } - - public int getHeight() { - return image.getHeight(); - } - - public int getScaledWidth() { - return scaledImage.getWidth(); - } - - public int getScaledHeight() { - return scaledImage.getHeight(); - } - - public void writeScaledData(OutputStream aStream, String anImageType) { - JAI.create("encode", scaledImage, aStream, anImageType, null); - } - - public byte[] getScaledData(String anImageType) { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - writeScaledData(outputStream, anImageType); - return outputStream.toByteArray(); - } - - public void writeScaledData(File aFile, String anImageType) throws IOException { - writeScaledData(new BufferedOutputStream(new FileOutputStream(aFile),8192), anImageType); - } -} - - - - - - - - - - - - - - - - - - - - +/* + * 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 mir.media.image; + +import com.sun.media.jai.codec.ByteArraySeekableStream; +import com.sun.media.jai.codec.FileSeekableStream; +import com.sun.media.jai.codec.SeekableStream; +import mir.log.LoggerWrapper; +import mir.media.MediaExc; +import mir.media.MediaFailure; + +import javax.media.jai.ImageLayout; +import javax.media.jai.InterpolationBilinear; +import javax.media.jai.JAI; +import javax.media.jai.ParameterBlockJAI; +import java.awt.*; +import java.awt.image.ColorModel; +import java.awt.image.DataBuffer; +import java.awt.image.PixelInterleavedSampleModel; +import java.awt.image.RenderedImage; +import java.io.*; + +public class JAIImageProcessor implements ImageProcessor { + static final LoggerWrapper logger = new LoggerWrapper("media.image.jai"); + + private RenderedImage image; + private RenderedImage scaledImage; + + public JAIImageProcessor(RenderedImage anImage) { + image = anImage; + scaledImage = anImage; + } + + public JAIImageProcessor(SeekableStream anImageStream) { + RenderedImage tempImage = JAI.create("stream", anImageStream); + ParameterBlockJAI params = new ParameterBlockJAI("format"); + int bands[]; + int nrComponents; + + + params.addSource(tempImage); + params.setParameter("dataType", DataBuffer.TYPE_BYTE); + + ImageLayout layout = new ImageLayout(); + nrComponents = tempImage.getColorModel().getNumColorComponents(); + + bands = new int[nrComponents]; + for (int i=0; i0 && image.getWidth()>aMaxWidth+aMinResize-1) || (aMaxHeight>0 && image.getHeight()>aMaxHeight+aMinResize-1)) + { + logger.info("Scaling image"); + + scale=1; + + if (aMaxWidth>0 && image.getWidth()>aMaxWidth) { + scale = Math.min(scale, (float) aMaxWidth / (float) image.getWidth()); + } + if (aMaxHeight>0 && image.getHeight()>aMaxHeight) { + scale = Math.min(scale, (float) aMaxHeight / (float) image.getHeight()); + } + + if (1-scale>aMinDescale) { + scaleImage(scale); + } + } + } + + public void scaleImage(float aScalingFactor) throws MediaExc { + ParameterBlockJAI params = new ParameterBlockJAI("scale"); + params.addSource(image); + + params.setParameter("xScale", aScalingFactor); + params.setParameter("yScale", aScalingFactor); + params.setParameter("xTrans", 0.0F); + params.setParameter("yTrans", 0.0F); + params.setParameter("interpolation", new InterpolationBilinear()); + scaledImage = JAI.create("scale", params); + } + + public int getWidth() { + return image.getWidth(); + } + + public int getHeight() { + return image.getHeight(); + } + + public int getScaledWidth() { + return scaledImage.getWidth(); + } + + public int getScaledHeight() { + return scaledImage.getHeight(); + } + + public void writeScaledData(OutputStream aStream, String anImageType) { + JAI.create("encode", scaledImage, aStream, anImageType, null); + } + + public byte[] getScaledData(String anImageType) { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + writeScaledData(outputStream, anImageType); + return outputStream.toByteArray(); + } + + public void writeScaledData(File aFile, String anImageType) throws MediaExc { + try { + writeScaledData(new BufferedOutputStream(new FileOutputStream(aFile),8192), anImageType); + } + catch (FileNotFoundException f) { + throw new MediaFailure(f); + } + } +} + + + + + + + + + + + + + + + + + + + + diff --git a/source/mir/module/AbstractModule.java b/source/mir/module/AbstractModule.java index 4b38727b..eb4f9dab 100755 --- a/source/mir/module/AbstractModule.java +++ b/source/mir/module/AbstractModule.java @@ -29,13 +29,11 @@ */ package mir.module; -import java.sql.SQLException; -import java.util.Map; - import mir.entity.Entity; import mir.entity.EntityList; import mir.storage.Database; +import java.util.Map; /** * This class provides the base functionality for the derived Module-Classes. @@ -90,13 +88,6 @@ public class AbstractModule { } } - /** - * * Standardfunktion, um einen Datensatz via Database einzuf?gen - * @param theValues Hash mit Spalte/Wert-Paaren - * @return Id des eingef?gten Objekts - * @exception ModuleExc - * @exception ModuleFailure - */ public String add(Map theValues) throws ModuleExc, ModuleFailure { try { Entity entity = database.createNewEntity(); @@ -109,13 +100,6 @@ public class AbstractModule { } } - /** - * Standardfunktion, um einen Datensatz via Database zu aktualisieren - * @param theValues Hash mit Spalte/Wert-Paaren - * @return Id des eingef?gten Objekts - * @exception ModuleExc - * @exception ModuleFailure - */ public String set (Map theValues) throws ModuleExc, ModuleFailure { try { Entity theEntity = database.selectById((String) theValues.get("id")); @@ -144,17 +128,4 @@ public class AbstractModule { throw new ModuleFailure(e); } } - - /** - * returns the number of rows - */ - public int getSize(String where) throws ModuleExc, ModuleFailure { - try { - return database.getSize(where); - } - catch (SQLException e) { - throw new ModuleFailure("Can't retrieve number of entities: " + e.toString(), e); - } - } - } diff --git a/source/mir/servlet/AbstractServlet.java b/source/mir/servlet/AbstractServlet.java index 55648f35..1a90e763 100755 --- a/source/mir/servlet/AbstractServlet.java +++ b/source/mir/servlet/AbstractServlet.java @@ -52,7 +52,7 @@ import mircoders.global.MirGlobal; * Copyright: Copyright (c) 2001, 2002 * Company: Mir-coders group * @author idfx, the Mir-coders group - * @version $Id: AbstractServlet.java,v 1.30.2.7 2004/11/21 22:07:13 zapata Exp $ + * @version $Id: AbstractServlet.java,v 1.30.2.8 2005/03/26 11:26:24 zapata Exp $ */ public abstract class AbstractServlet extends HttpServlet { @@ -64,11 +64,6 @@ public abstract class AbstractServlet extends HttpServlet { } protected void setNoCaching(HttpServletResponse aResponse) { - //nothing in Mir can or should be cached as it's all dynamic... - // - //this needs to be done here and not per page (via meta tags) as some - //browsers have problems w/ it per-page -mh - aResponse.setHeader("Pragma", "no-cache"); aResponse.setDateHeader("Expires", 0); aResponse.setHeader("Cache-Control", "no-cache"); @@ -78,26 +73,11 @@ public abstract class AbstractServlet extends HttpServlet { * Bind the language to the session */ protected void setLanguage(HttpSession session, String language) { - logger.debug("setting language to " + language); - session.setAttribute("language", language); session.setAttribute("locale", new Locale(language, "")); } /** - * Get the session-bound language - */ - protected String getLanguage(HttpServletRequest aRequest, HttpSession session) { - String language = (String) session.getAttribute("language"); - - if (language == null || language.length()==0) { - language = getAcceptLanguage(aRequest); - } - - return language; - } - - /** * get the locale either from the session or the accept-language header ot the request * this supersedes getLanguage for the new i18n */ @@ -124,18 +104,19 @@ public abstract class AbstractServlet extends HttpServlet { * else it returns the standard-language */ protected String getAcceptLanguage(HttpServletRequest aRequest) { - Locale loc = aRequest.getLocale(); - String lang = loc.getLanguage(); - return lang; + Locale locale = aRequest.getLocale(); + String language = locale.getLanguage(); + + return language; } /** * @see javax.servlet.Servlet#init(javax.servlet.ServletConfig) */ - public void init(ServletConfig config) throws ServletException { - super.init(config); + public void init(ServletConfig aConfiguration) throws ServletException { + super.init(aConfiguration); - MirPropertiesConfiguration.setContext(config.getServletContext()); + MirPropertiesConfiguration.setContext(aConfiguration.getServletContext()); try { configuration = MirPropertiesConfiguration.instance(); } @@ -164,18 +145,19 @@ public abstract class AbstractServlet extends HttpServlet { } } - private void setEncoding(HttpServletRequest request){ + private void setEncoding(HttpServletRequest aRequest) { try { - logger.info("Request has encoding: " + request.getCharacterEncoding()); + logger.info("Request has encoding: " + aRequest.getCharacterEncoding()); logger.info("Config stipulates encoding: " + configuration.getString("Mir.DefaultHTMLCharset")); - Class reqClass = request.getClass(); - Method method = reqClass.getMethod("setCharacterEncoding", new Class[]{String.class}); + + Class requestClass = aRequest.getClass(); + Method method = requestClass.getMethod("setCharacterEncoding", new Class[]{String.class}); String encoding = configuration.getString("Mir.DefaultHTMLCharset"); - method.invoke(request, new Object[]{encoding}); - logger.info("Request now has encoding: " + request.getCharacterEncoding()); + method.invoke(aRequest, new Object[]{encoding}); + logger.info("Request now has encoding: " + aRequest.getCharacterEncoding()); } catch (NoSuchMethodException e) { - // TODO set the encoding in a zapata-way + // TODO do something to support old servlet containers } catch (SecurityException e) { logger.error(e.getMessage()); @@ -203,6 +185,7 @@ public abstract class AbstractServlet extends HttpServlet { if ((configuration.getString("RootUri") == null) || configuration.getString("RootUri").equals("")) { configuration.setProperty("RootUri", request.getContextPath()); } + setEncoding(request); process(request, response); } diff --git a/source/mir/servlet/ServletModule.java b/source/mir/servlet/ServletModule.java index 13553f3b..30aadc52 100755 --- a/source/mir/servlet/ServletModule.java +++ b/source/mir/servlet/ServletModule.java @@ -161,7 +161,7 @@ public abstract class ServletModule { public String getDefaultListOrdering() { if (mainModule!=null && mainModule.getStorageObject()!=null) { - if (mainModule.getStorageObject().getFieldNames().contains("webdb_create")) + if (mainModule.getStorageObject().hasField("webdb_create")) return "webdb_create desc"; } diff --git a/source/mir/servlet/ServletModuleDispatch.java b/source/mir/servlet/ServletModuleDispatch.java index f5e841bb..5661acfc 100755 --- a/source/mir/servlet/ServletModuleDispatch.java +++ b/source/mir/servlet/ServletModuleDispatch.java @@ -42,10 +42,9 @@ import mir.log.LoggerWrapper; * Dispatcher, calls the method passed to ServletModule Class, through the "do" * Parameter (via POST or GET) * - * @version $Id: ServletModuleDispatch.java,v 1.15.2.1 2003/09/03 17:49:38 zapata Exp $ - * - * @Author rk + * @version $Id: ServletModuleDispatch.java,v 1.15.2.2 2005/03/26 11:26:25 zapata Exp $ * + * @author rk */ public final class ServletModuleDispatch { @@ -66,15 +65,14 @@ public final class ServletModuleDispatch { * @param aRequest * @param aResponse * @throws ServletModuleExc - * @throws ServletModuleUserExc * @throws ServletModuleFailure */ public static void dispatch(ServletModule aServletModule, HttpServletRequest aRequest, - HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure - { + HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleFailure { String doParam = aRequest.getParameter("do"); - logger.info("ServletModuleDispatch: " + aServletModule.toString() + " with method " + doParam); + logger.debug("ServletModuleDispatch: " + aServletModule.toString() + " with method " + doParam); + if (doParam == null) { if (aServletModule.defaultAction() != null) doParam = aServletModule.defaultAction(); diff --git a/source/mir/storage/Database.java b/source/mir/storage/Database.java index 089a3a7c..3cb74013 100755 --- a/source/mir/storage/Database.java +++ b/source/mir/storage/Database.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2001, 2002 The Mir-coders group + * Copyright (C) 2001-2005 The Mir-coders group * * This file is part of Mir. * @@ -29,28 +29,6 @@ */ package mir.storage; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Timestamp; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.TimeZone; - import mir.config.MirPropertiesConfiguration; import mir.entity.AbstractEntity; import mir.entity.Entity; @@ -58,59 +36,55 @@ import mir.entity.EntityList; import mir.entity.StorableObjectEntity; import mir.log.LoggerWrapper; import mir.misc.StringUtil; -import mir.storage.store.ObjectStore; -import mir.storage.store.StorableObject; -import mir.storage.store.StoreContainerType; -import mir.storage.store.StoreIdentifier; -import mir.storage.store.StoreUtil; +import mir.storage.store.*; import mir.util.JDBCStringRoutines; +import mir.util.StreamCopier; import mircoders.global.MirGlobal; - import org.apache.commons.dbcp.DelegatingConnection; import org.postgresql.PGConnection; import org.postgresql.largeobject.LargeObject; import org.postgresql.largeobject.LargeObjectManager; +import java.io.*; +import java.sql.*; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.*; + /** * Implements database access. * - * @version $Id: Database.java,v 1.44.2.29 2005/03/15 21:21:36 john Exp $ + * @version $Id: Database.java,v 1.44.2.30 2005/03/26 11:26:25 zapata Exp $ * @author rk + * @author Zapata * */ public class Database { + private static int DEFAULT_LIMIT = 20; private static Class GENERIC_ENTITY_CLASS = mir.entity.StorableObjectEntity.class; protected static final ObjectStore o_store = ObjectStore.getInstance(); private static final int _millisPerHour = 60 * 60 * 1000; protected LoggerWrapper logger; - protected MirPropertiesConfiguration configuration; protected String mainTable; - protected String primaryKeySequence = null; protected String primaryKeyField = "id"; protected List fieldNames; - protected int[] fieldTypes; - protected Map fieldNameToType; + private int[] fieldTypes; + private Map fieldNameToType; protected Class entityClass; - private int defaultLimit; + + // + private Set binaryFields; TimeZone timezone; SimpleDateFormat internalDateFormat; SimpleDateFormat userInputDateFormat; - /** - * Kontruktor bekommt den Filenamen des Konfigurationsfiles ?bergeben. - * Aus diesem file werden Database.Logfile, - * Database.Username,Database.Password, - * Database.Host und Database.Adaptor - * ausgelesen und ein Broker f?r die Verbindugen zur Datenbank - * erzeugt. - */ - public Database() throws StorageObjectFailure { - configuration = MirPropertiesConfiguration.instance(); + public Database() throws DatabaseFailure { + MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance(); logger = new LoggerWrapper("Database"); timezone = TimeZone.getTimeZone(configuration.getString("Mir.DefaultTimezone")); internalDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @@ -119,23 +93,24 @@ public class Database { userInputDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); userInputDateFormat.setTimeZone(timezone); + binaryFields = new HashSet(); + String theAdaptorName = configuration.getString("Database.Adaptor"); - defaultLimit = Integer.parseInt(configuration.getString("Database.Limit")); try { entityClass = GENERIC_ENTITY_CLASS; } catch (Throwable e) { logger.error("Error in Database() constructor with " + theAdaptorName + " -- " + e.getMessage()); - throw new StorageObjectFailure("Error in Database() constructor.", e); + throw new DatabaseFailure("Error in Database() constructor.", e); } } - public java.lang.Class getEntityClass() { + public Class getEntityClass() { return entityClass; } - public Entity createNewEntity() throws StorageObjectFailure { + public Entity createNewEntity() throws DatabaseFailure { try { AbstractEntity result = (AbstractEntity) entityClass.newInstance(); result.setStorage(this); @@ -143,51 +118,22 @@ public class Database { return result; } catch (Throwable t) { - throw new StorageObjectFailure(t); + throw new DatabaseFailure(t); } } - /** - * Liefert die Standardbeschr?nkung von select-Statements zur?ck, also - * wieviel Datens?tze per Default selektiert werden. - * - * @return Standard-Anzahl der Datens?tze - */ - public int getLimit() { - return defaultLimit; - } - public String getIdFieldName() { return primaryKeyField; } - /** - * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht. - * - * @return Name der Tabelle - */ public String getTableName() { return mainTable; } /** - * Returns the id that was most recently added to the database - */ - private String getLatestInsertedId(Connection aConnection) throws SQLException { - if (primaryKeySequence==null) - primaryKeySequence = mainTable+"_id_seq"; - - PreparedStatement statement = aConnection.prepareStatement("select currval('" + primaryKeySequence + "')"); - - ResultSet rs = statement.executeQuery(); - rs.next(); - return rs.getString(1); - } - - /** * Returns a list of field names for this Database */ - public List getFieldNames() throws StorageObjectFailure { + public List getFieldNames() throws DatabaseFailure { if (fieldNames == null) { acquireMetaData(); } @@ -195,23 +141,28 @@ public class Database { return fieldNames; } + public boolean hasField(String aFieldName) { + return getFieldNames().contains(aFieldName); + } + /** * Gets value out of ResultSet according to type and converts to String - * @param rs ResultSet. + * + * @param aResultSet ResultSet. * @param aType a type from java.sql.Types.* - * @param valueIndex index in ResultSet + * @param aFieldIndex index in ResultSet * @return returns the value as String. If no conversion is possible * /unsupported value/ is returned */ - private String getValueAsString(ResultSet rs, int valueIndex, int aType) - throws StorageObjectFailure { + private String getValueAsString(ResultSet aResultSet, int aFieldIndex, int aType) + throws DatabaseFailure { String outValue = null; - if (rs != null) { + if (aResultSet != null) { try { switch (aType) { case java.sql.Types.BIT: - outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0"; + outValue = (aResultSet.getBoolean(aFieldIndex) == true) ? "1" : "0"; break; @@ -220,21 +171,20 @@ public class Database { case java.sql.Types.TINYINT: case java.sql.Types.BIGINT: - int out = rs.getInt(valueIndex); + int out = aResultSet.getInt(aFieldIndex); - if (!rs.wasNull()) { + if (!aResultSet.wasNull()) { outValue = new Integer(out).toString(); } break; case java.sql.Types.NUMERIC: - /** todo Numeric can be float or double depending upon * metadata.getScale() / especially with oracle */ - long outl = rs.getLong(valueIndex); + long outl = aResultSet.getLong(aFieldIndex); - if (!rs.wasNull()) { + if (!aResultSet.wasNull()) { outValue = new Long(outl).toString(); } @@ -242,9 +192,9 @@ public class Database { case java.sql.Types.REAL: - float tempf = rs.getFloat(valueIndex); + float tempf = aResultSet.getFloat(aFieldIndex); - if (!rs.wasNull()) { + if (!aResultSet.wasNull()) { tempf *= 10; tempf += 0.5; @@ -259,9 +209,9 @@ public class Database { case java.sql.Types.DOUBLE: - double tempd = rs.getDouble(valueIndex); + double tempd = aResultSet.getDouble(aFieldIndex); - if (!rs.wasNull()) { + if (!aResultSet.wasNull()) { tempd *= 10; tempd += 0.5; @@ -277,12 +227,12 @@ public class Database { case java.sql.Types.CHAR: case java.sql.Types.VARCHAR: case java.sql.Types.LONGVARCHAR: - outValue = rs.getString(valueIndex); + outValue = aResultSet.getString(aFieldIndex); break; case java.sql.Types.LONGVARBINARY: - outValue = rs.getString(valueIndex); + outValue = aResultSet.getString(aFieldIndex); break; @@ -292,9 +242,9 @@ public class Database { // as a string is undefined and is only there for debugging // according to the API. we can make it a string through formatting. // -mh - Timestamp timestamp = (rs.getTimestamp(valueIndex)); + Timestamp timestamp = (aResultSet.getTimestamp(aFieldIndex)); - if (!rs.wasNull()) { + if (!aResultSet.wasNull()) { java.util.Date date = new java.util.Date(timestamp.getTime()); Calendar calendar = new GregorianCalendar(); @@ -316,10 +266,10 @@ public class Database { default: outValue = ""; - logger.warn("Unsupported Datatype: at " + valueIndex + " (" + aType + ")"); + logger.warn("Unsupported Datatype: at " + aFieldIndex + " (" + aType + ")"); } } catch (SQLException e) { - throw new StorageObjectFailure("Could not get Value out of Resultset -- ", + throw new DatabaseFailure("Could not get Value out of Resultset -- ", e); } } @@ -328,18 +278,16 @@ public class Database { } /** - * select-Operator um einen Datensatz zu bekommen. - * @param id Primaerschluessel des Datensatzes. - * @return liefert EntityObject des gefundenen Datensatzes oder null. + * Return an entity specified by id */ - public Entity selectById(String id) throws StorageObjectExc { - if ((id == null) || id.equals("")) { - throw new StorageObjectExc("Database.selectById: Missing id"); + public Entity selectById(String anId) throws DatabaseExc { + if ((anId == null) || anId.equals("")) { + throw new DatabaseExc("Database.selectById: Missing id"); } // ask object store for object if (StoreUtil.extendsStorableEntity(entityClass)) { - String uniqueId = id; + String uniqueId = anId; if (entityClass.equals(StorableObjectEntity.class)) { uniqueId += ("@" + mainTable); @@ -355,172 +303,97 @@ public class Database { } } - Statement stmt = null; Connection con = obtainConnection(); Entity returnEntity = null; + PreparedStatement statement = null; try { ResultSet rs; + String query = "select * from " + mainTable + " where " + primaryKeyField + " = ?"; - /** todo better prepared statement */ - String selectSql = - "select * from " + mainTable + " where " + primaryKeyField + "=" + id; - stmt = con.createStatement(); - rs = executeSql(stmt, selectSql); + statement = con.prepareStatement(query); + statement.setString(1, anId); + + logQueryBefore(query); + + long startTime = System.currentTimeMillis(); + try { + rs = statement.executeQuery(); + + logQueryAfter(query, (System.currentTimeMillis() - startTime)); + } + catch (SQLException e) { + logQueryError(query, (System.currentTimeMillis() - startTime), e); + throw e; + } if (rs != null) { if (rs.next()) { returnEntity = makeEntityFromResultSet(rs); } else { - logger.warn("No data for id: " + id + " in table " + mainTable); + logger.warn("No data for id: " + anId + " in table " + mainTable); } rs.close(); } else { - logger.warn("No Data for Id " + id + " in Table " + mainTable); + logger.warn("No Data for Id " + anId + " in Table " + mainTable); } } - catch (SQLException sqe) { - throwSQLException(sqe, "selectById"); - return null; - } - catch (NumberFormatException e) { - logger.error("ID is no number: " + id); + catch (Throwable e) { + throw new DatabaseFailure(e); } finally { - freeConnection(con, stmt); + freeConnection(con, statement); } return returnEntity; } - /** - * This method makes it possible to make selects across multiple tables - * - * @param mainTablePrefix prefix for the mainTable - * @param extraTables a vector of tables for relational select - * @param aWhereClause whereClause - * @return EntityList of selected Objects - * @throws StorageObjectFailure - */ - - public EntityList selectByWhereClauseWithExtraTables(String mainTablePrefix, - List extraTables, String aWhereClause ) - throws StorageObjectFailure { - return selectByWhereClause( mainTablePrefix, extraTables, aWhereClause, "", 0, defaultLimit); + public EntityList selectByWhereClauseWithExtraTables(String mainTablePrefix, List extraTables, String aWhereClause) throws DatabaseExc, DatabaseFailure { + return selectByWhereClause( mainTablePrefix, extraTables, aWhereClause, "", 0, DEFAULT_LIMIT); } - public EntityList selectByFieldValue(String aField, String aValue) throws StorageObjectFailure { + public EntityList selectByFieldValue(String aField, String aValue) throws DatabaseExc, DatabaseFailure { return selectByFieldValue(aField, aValue, 0); } - public EntityList selectByFieldValue(String aField, String aValue, int offset) throws StorageObjectFailure { + public EntityList selectByFieldValue(String aField, String aValue, int offset) throws DatabaseExc, DatabaseFailure { return selectByWhereClause(aField + "='" + JDBCStringRoutines.escapeStringLiteral(aValue)+"'", offset); } - /** - * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. - * Also offset wird der erste Datensatz genommen. - * - * @param where where-Clause - * @return EntityList mit den gematchten Entities - * @exception StorageObjectFailure - */ - public EntityList selectByWhereClause(String where) throws StorageObjectFailure { + public EntityList selectByWhereClause(String where) throws DatabaseExc, DatabaseFailure { return selectByWhereClause(where, 0); } - /** - * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. - * Als maximale Anzahl wird das Limit auf der Konfiguration genommen. - * - * @param whereClause where-Clause - * @param offset ab welchem Datensatz. - * @return EntityList mit den gematchten Entities - * @exception StorageObjectFailure - */ - public EntityList selectByWhereClause(String whereClause, int offset) throws StorageObjectFailure { + public EntityList selectByWhereClause(String whereClause, int offset) throws DatabaseExc, DatabaseFailure { return selectByWhereClause(whereClause, null, offset); } - /** - * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. - * Also offset wird der erste Datensatz genommen. - * Als maximale Anzahl wird das Limit auf der Konfiguration genommen. - * - * @param where where-Clause - * @param order orderBy-Clause - * @return EntityList mit den gematchten Entities - * @exception StorageObjectFailure - */ - public EntityList selectByWhereClause(String where, String order) throws StorageObjectFailure { - return selectByWhereClause(where, order, 0); - } - - public EntityList selectByWhereClause(String mainTablePrefix, List extraTables, String where, String order) throws StorageObjectFailure { - return selectByWhereClause(mainTablePrefix, extraTables, where, order, 0, defaultLimit); + public EntityList selectByWhereClause(String mainTablePrefix, List extraTables, String where, String order) throws DatabaseExc, DatabaseFailure { + return selectByWhereClause(mainTablePrefix, extraTables, where, order, 0, DEFAULT_LIMIT); } - /** - * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. - * Als maximale Anzahl wird das Limit auf der Konfiguration genommen. - * - * @param whereClause where-Clause - * @param orderBy orderBy-Clause - * @param offset ab welchem Datensatz - * @return EntityList mit den gematchten Entities - * @exception StorageObjectFailure - */ - public EntityList selectByWhereClause(String whereClause, String orderBy, int offset) throws StorageObjectFailure { - return selectByWhereClause(whereClause, orderBy, offset, defaultLimit); + public EntityList selectByWhereClause(String whereClause, String orderBy, int offset) throws DatabaseExc, DatabaseFailure { + return selectByWhereClause(whereClause, orderBy, offset, DEFAULT_LIMIT); } - /** - * select-Operator returns EntityList with matching rows in Database. - * @param aWhereClause where-Clause - * @param anOrderByClause orderBy-Clause - * @param offset ab welchem Datensatz - * @param limit wieviele Datens?tze - * @return EntityList mit den gematchten Entities - * @exception StorageObjectFailure - */ public EntityList selectByWhereClause(String aWhereClause, String anOrderByClause, - int offset, int limit) throws StorageObjectFailure { + int offset, int limit) throws DatabaseExc, DatabaseFailure { return selectByWhereClause("", null, aWhereClause, anOrderByClause, offset, limit); } - - /** - * select-Operator returns EntityList with matching rows in Database. - * @param aWhereClause where-Clause - * @param anOrderByClause orderBy-Clause - * @param anOffset ab welchem Datensatz - * @param aLimit wieviele Datens?tze - * @return EntityList mit den gematchten Entities - * @exception StorageObjectFailure - */ public EntityList selectByWhereClause( String aMainTablePrefix, List anExtraTables, String aWhereClause, String anOrderByClause, - int anOffset, int aLimit) throws StorageObjectFailure { - - // TODO get rid of emtpy Strings in anExtraTables - // make anExtraTables null, if single empty String in it - // cause StringUtil.splitString puts in emptyString + int anOffset, int aLimit) throws DatabaseExc, DatabaseFailure { if (anExtraTables!=null && ((String) anExtraTables.get(0)).trim().equals("")){ anExtraTables=null; } - String useTable = mainTable; - String selection = "*"; - - if (aMainTablePrefix != null && aMainTablePrefix.trim().length() > 0) { - useTable += " " + aMainTablePrefix; - selection = aMainTablePrefix.trim() + ".*"; - } + RecordRetriever retriever = new RecordRetriever(mainTable, aMainTablePrefix); // check o_store for entitylist // only if no relational select @@ -538,101 +411,94 @@ public class Database { } } - // local - EntityList theReturnList = null; + EntityList result = null; Connection connection = null; - Statement statement = null; - ResultSet resultSet; - // build sql-statement - - if ((aWhereClause != null) && (aWhereClause.trim().length() == 0)) { - aWhereClause = null; - } - - StringBuffer selectSql = - new StringBuffer("select "+selection+" from ").append(useTable); - - // append extratables, if necessary if (anExtraTables!=null) { - for (int i=0;i < anExtraTables.size();i++) { - if (!anExtraTables.get(i).equals("")) { - selectSql.append( ", " + anExtraTables.get(i)); + Iterator i = anExtraTables.iterator(); + while (i.hasNext()) { + String table = (String) i.next(); + if (!"".equals(table)) { + retriever.addExtraTable(table); } } } if (aWhereClause != null) { - selectSql.append(" where ").append(aWhereClause); + retriever.appendWhereClause(aWhereClause); } if ((anOrderByClause != null) && !(anOrderByClause.trim().length() == 0)) { - selectSql.append(" order by ").append(anOrderByClause); + retriever.appendOrderByClause(anOrderByClause); } - if ((aLimit > -1) && (anOffset > -1)) { - selectSql.append(" LIMIT ").append(aLimit+1).append(" OFFSET ").append(anOffset); + if (anOffset>-1 && aLimit>-1) { + retriever.setLimit(aLimit+1); + retriever.setOffset(anOffset); + } + + Iterator i = getFieldNames().iterator(); + while (i.hasNext()) { + retriever.addField((String) i.next()); } // execute sql try { connection = obtainConnection(); - statement = connection.createStatement(); - boolean hasMore = false; + ResultSet resultSet = retriever.execute(connection); - // selecting... - resultSet = executeSql(statement, selectSql.toString()); + boolean hasMore = false; if (resultSet != null) { - theReturnList = new EntityList(); - Entity theResultEntity; + result = new EntityList(); + Entity entity; int position = 0; + while (((aLimit == -1) || (position= 10) { @@ -875,92 +670,76 @@ public class Database { // TimeStamp stuff try { java.util.Date d = userInputDateFormat.parse(dateString); -// Timestamp tStamp = new Timestamp(d.getTime()); - sql.append(",webdb_create='" + JDBCStringRoutines.formatDate(d) + "'"); + generator.assignDate("webdb_create", d); } catch (ParseException e) { - throw new StorageObjectFailure(e); + throw new DatabaseFailure(e); } } } - sql.append(" where id=").append(id); - logQueryBefore(sql.toString()); - try { - con = obtainConnection(); - con.setAutoCommit(false); - pstmt = con.prepareStatement(sql.toString()); - - pstmt.executeUpdate(); - } - catch (SQLException sqe) { - throwSQLException(sqe, "update"); + connection = obtainConnection(); + generator.execute(connection); } finally { - try { - con.setAutoCommit(true); - } - catch (Exception e) { - - - } - - freeConnection(con, pstmt); + freeConnection(connection); } } - - /* - * delete-Operator - * @param id des zu loeschenden Datensatzes - * @return boolean liefert true zurueck, wenn loeschen erfolgreich war. - */ - public boolean delete(String id) throws StorageObjectFailure { + + private void invalidateObject(String anId) { // ostore send notification if (StoreUtil.extendsStorableEntity(entityClass)) { - String uniqueId = id; + String uniqueId = anId; if (entityClass.equals(StorableObjectEntity.class)) { uniqueId += ("@" + mainTable); } - logger.debug("CACHE: (del) " + id); + logger.debug("CACHE: (del) " + anId); StoreIdentifier search_sid = new StoreIdentifier(entityClass, StoreContainerType.STOC_TYPE_ENTITY, uniqueId); o_store.invalidate(search_sid); } + } + /* + * delete-Operator + * @param id des zu loeschenden Datensatzes + * @return boolean liefert true zurueck, wenn loeschen erfolgreich war. + */ + public boolean delete(String id) throws DatabaseFailure { + invalidateObject(id); + /** todo could be prepared Statement */ - Statement stmt = null; - Connection con = null; - int res = 0; - String sql = - "delete from " + mainTable + " where " + primaryKeyField + "='" + id + "'"; + int resultCode = 0; + Connection connection = obtainConnection(); + PreparedStatement statement = null; - logQueryBefore(sql); try { - con = obtainConnection(); - stmt = con.createStatement(); - res = stmt.executeUpdate(sql); + statement = connection.prepareStatement("delete from " + mainTable + " where " + primaryKeyField + "=?"); + statement.setInt(1, Integer.parseInt(id)); + logQueryBefore("delete from " + mainTable + " where " + primaryKeyField + "=" + id + ""); + resultCode = statement.executeUpdate(); } - catch (SQLException sqe) { - throwSQLException(sqe, "delete"); + catch (SQLException e) { + logger.warn("Can't delete record", e); } finally { - freeConnection(con, stmt); + freeConnection(connection, statement); } invalidateStore(); - return (res > 0) ? true : false; + return (resultCode > 0) ? true : false; } /** * Deletes entities based on a where clause */ - public int deleteByWhereClause(String aWhereClause) throws StorageObjectFailure { + public int deleteByWhereClause(String aWhereClause) throws DatabaseFailure { invalidateStore(); Statement stmt = null; @@ -975,8 +754,8 @@ public class Database { stmt = con.createStatement(); res = stmt.executeUpdate(sql); } - catch (SQLException sqe) { - throwSQLException(sqe, "delete"); + catch (Throwable e) { + throw new DatabaseFailure(e); } finally { freeConnection(con, stmt); @@ -992,13 +771,8 @@ public class Database { return false; } - /** - * Diese Methode fuehrt den Sqlstring sql aus und timed im Logfile. - * @param stmt Statemnt - * @param sql Sql-String - */ public ResultSet executeSql(Statement stmt, String sql) - throws StorageObjectFailure, SQLException { + throws DatabaseFailure, SQLException { ResultSet rs; logQueryBefore(sql); long startTime = System.currentTimeMillis(); @@ -1015,7 +789,7 @@ public class Database { return rs; } - private Map processRow(ResultSet aResultSet) throws StorageObjectFailure { + private Map processRow(ResultSet aResultSet) throws DatabaseFailure { try { Map result = new HashMap(); ResultSetMetaData metaData = aResultSet.getMetaData(); @@ -1027,7 +801,7 @@ public class Database { return result; } catch (Throwable e) { - throw new StorageObjectFailure(e); + throw new DatabaseFailure(e); } } @@ -1035,7 +809,7 @@ public class Database { * Executes 1 sql statement and returns the results as a List of * Maps */ - public List executeFreeSql(String sql, int aLimit) throws StorageObjectFailure, StorageObjectExc { + public List executeFreeSql(String sql, int aLimit) throws DatabaseFailure, DatabaseExc { Connection connection = null; Statement statement = null; try { @@ -1055,7 +829,7 @@ public class Database { return result; } catch (Throwable e) { - throw new StorageObjectFailure(e); + throw new DatabaseFailure(e); } finally { if (connection!=null) { @@ -1068,7 +842,7 @@ public class Database { * Executes 1 sql statement and returns the first result row as a Maps * (null if there wasn't any row) */ - public Map executeFreeSingleRowSql(String anSqlStatement) throws StorageObjectFailure, StorageObjectExc { + public Map executeFreeSingleRowSql(String anSqlStatement) throws DatabaseFailure, DatabaseExc { try { List resultList = executeFreeSql(anSqlStatement, 1); try { @@ -1080,7 +854,7 @@ public class Database { } } catch (Throwable t) { - throw new StorageObjectFailure(t); + throw new DatabaseFailure(t); } } @@ -1088,7 +862,7 @@ public class Database { * Executes 1 sql statement and returns the first column of the first result row as a Strings * (null if there wasn't any row) */ - public String executeFreeSingleValueSql(String sql) throws StorageObjectFailure, StorageObjectExc { + public String executeFreeSingleValueSql(String sql) throws DatabaseFailure, DatabaseExc { Map row = executeFreeSingleRowSql(sql); if (row==null) @@ -1100,13 +874,13 @@ public class Database { return null; } - public int getSize(String where) throws SQLException, StorageObjectFailure { + public int getSize(String where) throws SQLException, DatabaseFailure { return getSize("", null, where); } /** * returns the number of rows in the table */ - public int getSize(String mainTablePrefix, List extraTables, String where) throws SQLException, StorageObjectFailure { + public int getSize(String mainTablePrefix, List extraTables, String where) throws SQLException, DatabaseFailure { String useTable = mainTable; if (mainTablePrefix!=null && mainTablePrefix.trim().length()>0) { @@ -1155,7 +929,7 @@ public class Database { } public int executeUpdate(Statement stmt, String sql) - throws StorageObjectFailure, SQLException { + throws DatabaseFailure, SQLException { int rs; logQueryBefore(sql); @@ -1175,7 +949,7 @@ public class Database { } public int executeUpdate(String sql) - throws StorageObjectFailure, SQLException { + throws DatabaseFailure, SQLException { int result = -1; Connection con = null; PreparedStatement pstmt = null; @@ -1190,7 +964,7 @@ public class Database { } catch (Throwable e) { logQueryError(sql, System.currentTimeMillis() - startTime, e); - throw new StorageObjectFailure("Database.executeUpdate(" + sql + "): " + e.getMessage(), e); + throw new DatabaseFailure("Database.executeUpdate(" + sql + "): " + e.getMessage(), e); } finally { freeConnection(con, pstmt); @@ -1201,7 +975,7 @@ public class Database { /** * Processes the metadata for the table this Database object is responsible for. */ - private void processMetaData(ResultSetMetaData aMetaData) throws StorageObjectFailure { + private void processMetaData(ResultSetMetaData aMetaData) throws DatabaseFailure { fieldNames = new ArrayList(); fieldNameToType = new HashMap(); @@ -1215,15 +989,15 @@ public class Database { fieldNameToType.put(aMetaData.getColumnName(i), new Integer(aMetaData.getColumnType(i))); } } - catch (SQLException e) { - throwSQLException(e, "processMetaData"); + catch (Throwable e) { + throw new DatabaseFailure(e); } } /** * Retrieves metadata from the table this Database object represents */ - private void acquireMetaData() throws StorageObjectFailure { + private void acquireMetaData() throws DatabaseFailure { Connection connection = null; PreparedStatement statement = null; String sql = "select * from " + mainTable + " where 0=1"; @@ -1241,31 +1015,24 @@ public class Database { resultSet.close(); } } - catch (SQLException e) { - throwSQLException(e, "acquireMetaData"); + catch (Throwable e) { + throw new DatabaseFailure(e); } finally { freeConnection(connection, statement); } } - public Connection obtainConnection() throws StorageObjectFailure { + public Connection obtainConnection() throws DatabaseFailure { try { return MirGlobal.getDatabaseEngine().obtainConnection(); } catch (Exception e) { - throw new StorageObjectFailure(e); + throw new DatabaseFailure(e); } } - public void freeConnection(Connection aConnection, Statement aStatement) throws StorageObjectFailure { - try { - aStatement.close(); - } - catch (Throwable t) { - logger.warn("Can't close statemnet: " + t.toString()); - } - + public void freeConnection(Connection aConnection) throws DatabaseFailure { try { MirGlobal.getDatabaseEngine().releaseConnection(aConnection); } @@ -1274,53 +1041,26 @@ public class Database { } } - /** - * Wertet SQLException aus und wirft dannach eine StorageObjectException - * @param sqe SQLException - * @param aFunction Funktonsname, in der die SQLException geworfen wurde - */ - protected void throwSQLException(SQLException sqe, String aFunction) throws StorageObjectFailure { - String state = ""; - String message = ""; - int vendor = 0; - - if (sqe != null) { - state = sqe.getSQLState(); - message = sqe.getMessage(); - vendor = sqe.getErrorCode(); + public void freeConnection(Connection aConnection, Statement aStatement) throws DatabaseFailure { + try { + aStatement.close(); + } + catch (Throwable t) { + logger.warn("Can't close statemnet: " + t.toString()); } - String information = - "SQL Error: " + - "state= " + state + - ", vendor= " + vendor + - ", message=" + message + - ", function= " + aFunction; - - logger.error(information); - - throw new StorageObjectFailure(information, sqe); + freeConnection(aConnection); } protected void _throwStorageObjectException(Exception e, String aFunction) - throws StorageObjectFailure { + throws DatabaseFailure { if (e != null) { logger.error(e.getMessage() + aFunction); - throw new StorageObjectFailure(aFunction, e); + throw new DatabaseFailure(aFunction, e); } } - /** - * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach - * eine StorageObjectException - * @param aMessage Nachricht mit dem Fehler - * @exception StorageObjectFailure - */ - void throwStorageObjectException(String aMessage) throws StorageObjectFailure { - logger.error(aMessage); - throw new StorageObjectFailure(aMessage, null); - } /** * Invalidates any cached entity list @@ -1337,11 +1077,10 @@ public class Database { /** * Retrieves a binary value */ - public InputStream getBinaryField(String aQuery) throws StorageObjectFailure, SQLException { + public byte[] getBinaryField(String aQuery) throws DatabaseFailure, SQLException { Connection connection=null; Statement statement=null; InputStream inputStream; - InputStream imageInputStream = null; try { connection = obtainConnection(); @@ -1353,50 +1092,50 @@ public class Database { if(resultSet!=null) { if (resultSet.next()) { if (resultSet.getMetaData().getColumnType(1) == java.sql.Types.BINARY) { - byte[] data = resultSet.getBytes(1); - imageInputStream = new ByteArrayInputStream(data); + return resultSet.getBytes(1); } else { inputStream = resultSet.getBlob(1).getBinaryStream(); - imageInputStream = new BinaryFieldInputStream(inputStream, connection, statement); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + StreamCopier.copy(inputStream, outputStream); + return outputStream.toByteArray(); } } resultSet.close(); } } finally { + try { + connection.setAutoCommit(true); + } + catch (Throwable e) { + logger.error("EntityImages.getImage resetting transaction mode failed: " + e.toString()); + e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); + } + + try { + freeConnection(connection, statement); + } + catch (Throwable e) { + logger.error("EntityImages.getImage freeing connection failed: " +e.toString()); + } + } } catch (Throwable t) { logger.error("EntityImages.getImage failed: " + t.toString()); t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); - try { - connection.setAutoCommit(true); - } - catch (Throwable e) { - logger.error("EntityImages.getImage resetting transaction mode failed: " + e.toString()); - e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); - } - - try { - freeConnection(connection, statement); - } - catch (Throwable e) { - logger.error("EntityImages.getImage freeing connection failed: " +e.toString()); - } - - throw new StorageObjectFailure(t); + throw new DatabaseFailure(t); } - - return imageInputStream; + return new byte[0]; } /** * Sets a binary value for a particular field in a record specified by its identifier */ - public void setBinaryField(String aFieldName, String anObjectId, byte aData[]) throws StorageObjectFailure, SQLException { + public void setBinaryField(String aFieldName, String anObjectId, byte aData[]) throws DatabaseFailure, SQLException { PreparedStatement statement = null; Connection connection = obtainConnection(); @@ -1435,6 +1174,24 @@ public class Database { } } + /** + * Can be overridden to specify a primary key sequence name not named according to + * the convention (tablename _id_seq) + */ + protected String getPrimaryKeySequence() { + return mainTable+"_id_seq"; + } + + /** + * Can be called by subclasses to specify fields that are binary, and that shouldn't + * be updated outside of {@link #setBinaryField} + * + * @param aBinaryField The field name of the binary field + */ + protected void markBinaryField(String aBinaryField) { + binaryFields.add(aBinaryField); + } + private void logQueryBefore(String aQuery) { logger.debug("about to perform QUERY " + aQuery); // (new Throwable()).printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); @@ -1455,36 +1212,4 @@ public class Database { return ((Integer) fieldNameToType.get(aFieldName)).intValue(); } - - - /** - * a small wrapper class that allows us to store the DB connection resources - * that the BlobInputStream is using and free them upon closing of the stream - */ - private class BinaryFieldInputStream extends InputStream { - InputStream inputStream; - Connection connection; - Statement statement; - - public BinaryFieldInputStream(InputStream aBlobInputStream, Connection aConnection, Statement aStatement ) { - inputStream = aBlobInputStream; - connection = aConnection; - statement = aStatement; - } - - public void close () throws IOException { - inputStream.close(); - try { - connection.setAutoCommit(true); - freeConnection(connection, statement); - } - catch (Exception e) { - throw new IOException("close(): "+e.toString()); - } - } - - public int read() throws IOException { - return inputStream.read(); - } - } } diff --git a/source/mir/storage/StorageObjectExc.java b/source/mir/storage/DatabaseExc.java similarity index 88% rename from source/mir/storage/StorageObjectExc.java rename to source/mir/storage/DatabaseExc.java index 39a9970d..d8c777bb 100755 --- a/source/mir/storage/StorageObjectExc.java +++ b/source/mir/storage/DatabaseExc.java @@ -31,16 +31,8 @@ package mir.storage; import multex.Exc; - -/** - * @author idefix - */ -public class StorageObjectExc extends Exc { - public StorageObjectExc() { - super("Something gone wrong"); - } - - public StorageObjectExc(String msg) { - super(msg); +public class DatabaseExc extends Exc { + public DatabaseExc(String aMessage) { + super(aMessage); } } diff --git a/source/mir/storage/StorageObjectFailure.java b/source/mir/storage/DatabaseFailure.java similarity index 88% rename from source/mir/storage/StorageObjectFailure.java rename to source/mir/storage/DatabaseFailure.java index 3b946b9e..8bff0c01 100755 --- a/source/mir/storage/StorageObjectFailure.java +++ b/source/mir/storage/DatabaseFailure.java @@ -36,27 +36,27 @@ import multex.Failure; * Exception for all occuring failures in the database-layer * @author idefix */ -public class StorageObjectFailure extends Failure { +public class DatabaseFailure extends Failure { /** * Constructor StorageObjectException. * @param e */ - public StorageObjectFailure(Throwable e) { + public DatabaseFailure(Throwable e) { super("", e); } /** * Standard constructor */ - public StorageObjectFailure() { + public DatabaseFailure() { super("A failure occured", null); } /** - * Constructor with message - * @param msg + * Construktor with message + * @param String msg */ - public StorageObjectFailure(String msg, Throwable e) { + public DatabaseFailure(String msg, Throwable e) { super(msg, e); } } diff --git a/source/mir/storage/RecordInserter.java b/source/mir/storage/RecordInserter.java new file mode 100755 index 00000000..a4f8d8ea --- /dev/null +++ b/source/mir/storage/RecordInserter.java @@ -0,0 +1,114 @@ +/* + * Copyright (C) 2005 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 mir.storage; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Date; + +/** + * Class to generate insert statements + */ +public class RecordInserter extends StatementGenerator { + + public RecordInserter(String aTableName, String aSequenceName) { + tableName = aTableName; + sequenceName = aSequenceName; + } + + /** + * Assigns a value to a string typed field + */ + public void assignString(String aFieldName, String aValue) { + assignObject(aFieldName, aValue); + } + + /** + * Assigns a value to a date/time typed field + */ + public void assignDate(String aFieldName, Date aDate) { + assignObject(aFieldName, new java.sql.Date(aDate.getTime())); + } + + public void assignVerbatim(String aFieldName, String aText) { + if (firstAssignment) { + appendQuery("insert into " + tableName + "("); + firstAssignment = false; + } + else { + appendQuery(","); + values.append(","); + } + + values.append(aText); + + appendQuery(aFieldName); + } + + /** + * Executes the statement. Returns the id of the insterted record. + */ + public String execute(Connection aConnection) throws DatabaseFailure { + appendQuery(")"); + appendQuery(CRLF); + appendQuery("values ("); + appendQuery(values.toString()); + appendQuery(")"); + + try { + int modified = executeWithModifiedCount(aConnection); + if (modified!=1) { + throw new Exception("modified count != 1 after insert"); + } + + PreparedStatement statement = aConnection.prepareStatement("select currval('" + sequenceName + "')"); + ResultSet rs = statement.executeQuery(); + rs.next(); + return rs.getString(1); + } + catch (Throwable e) { + throw new DatabaseFailure(e); + } + } + + private void assignObject(String aFieldName, Object anObject) { + appendParameter(anObject); + + assignVerbatim(aFieldName, "?"); + } + + private String tableName; + private static final String CRLF = "\n\r"; + private boolean firstAssignment = true; + private String sequenceName; + private StringBuffer values = new StringBuffer(); +} \ No newline at end of file diff --git a/source/mir/storage/RecordRetriever.java b/source/mir/storage/RecordRetriever.java new file mode 100755 index 00000000..5b3f098b --- /dev/null +++ b/source/mir/storage/RecordRetriever.java @@ -0,0 +1,148 @@ +/* + * Copyright (C) 2005 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 mir.storage; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.util.*; + +/** + * Class to generate update statements + */ +public class RecordRetriever extends StatementGenerator { + public RecordRetriever(String aTableName, String aPrefix) { + tableName = aTableName; + prefix = aPrefix; + if (prefix == null || "".equals(prefix)) { + prefix = null; + } + extraTables = new ArrayList(); + whereClause = new StringBuffer(); + orderByClause = new StringBuffer(); + + appendQuery("SELECT "); + } + + public void addExtraTable(String aTableSpecification) { + extraTables.add(aTableSpecification); + } + + public void addField(String aField) { + if (firstField) { + firstField = false; + } + else { + appendQuery(", "); + } + if (prefix!=null) { + appendQuery(prefix); + appendQuery("."); + } + + appendQuery(aField); + } + + public void appendStringParameter(String aValue) { + appendParameter(aValue); + } + + public void appendWhereClause(String aPart) { + whereClause.append(aPart); + } + + public void appendOrderByClause(String aPart) { + orderByClause.append(aPart); + } + + public void setLimit(int aLimit) { + limit = aLimit; + } + + public void setOffset(int anOffset) { + offset = anOffset; + } + + /** + * Executes the statement. Returns then number of records + * changed + */ + public ResultSet execute(Connection aConnection) throws DatabaseFailure { + appendQuery(CRLF); + appendQuery("FROM "); + appendQuery(tableName); + if (prefix!=null) { + appendQuery(" "); + appendQuery(prefix); + } + + Iterator i = extraTables.iterator(); + while (i.hasNext()) { + appendQuery(", "); + appendQuery((String) i.next()); + } + + if (whereClause.toString().trim().length()>0) { + appendQuery(CRLF); + appendQuery("WHERE "); + appendQuery(whereClause.toString()); + } + + if (orderByClause.toString().trim().length()>0) { + appendQuery(CRLF); + appendQuery("ORDER BY "); + appendQuery(orderByClause.toString()); + } + + if (limit > -1) { + appendQuery(CRLF); + appendQuery("LIMIT "); + appendQuery(Integer.toString(limit)); + } + + if (offset > -1) { + appendQuery(CRLF); + appendQuery("OFFSET "); + appendQuery(Integer.toString(offset)); + } + + return executeWithResultSet(aConnection); + } + + private String tableName; + private String prefix; + private List extraTables; + private boolean firstField = true; + private StringBuffer whereClause; + private StringBuffer orderByClause; + private int limit = -1; + private int offset = -1; + + private static final String CRLF = "\n\r"; +} \ No newline at end of file diff --git a/source/mir/storage/RecordUpdater.java b/source/mir/storage/RecordUpdater.java new file mode 100755 index 00000000..e6920a0c --- /dev/null +++ b/source/mir/storage/RecordUpdater.java @@ -0,0 +1,96 @@ +/* + * Copyright (C) 2005 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 mir.storage; + +import java.sql.Connection; +import java.util.Date; + +/** + * Class to generate update statements + */ +public class RecordUpdater extends StatementGenerator{ + public RecordUpdater(String aTableName, String aRecordId) { + tableName = aTableName; + recordId = aRecordId; + } + + /** + * Assigns a value to a string typed field + */ + public void assignString(String aFieldName, String aValue) { + assignObject(aFieldName, aValue); + } + + /** + * Assigns a value to a date/time typed field + */ + public void assignDate(String aFieldName, Date aDate) { + assignObject(aFieldName, new java.sql.Date(aDate.getTime())); + } + + /** + * Assigns a verbatim value to a field. Use with case: no quoting/escaping + * will be performed + **/ + public void assignVerbatim(String aFieldName, String aValue) { + if (firstAssignment) { + appendQuery("update " + tableName + " set "); + firstAssignment = false; + } + else { + appendQuery(","); + } + + appendQuery(CRLF); + appendQuery(" " + aFieldName + " = " + aValue); + } + + /** + * Executes the statement. Returns then number of records + * changed + */ + public int execute(Connection aConnection) throws DatabaseFailure { + appendQuery(CRLF); + appendQuery("where id = ?"); + appendParameter(recordId); + + return executeWithModifiedCount(aConnection); + } + + private void assignObject(String aFieldName, Object anObject) { + appendParameter(anObject); + assignVerbatim(aFieldName, "?"); + } + + private String tableName; + private static final String CRLF = "\n\r"; + private String recordId; + private boolean firstAssignment = true; +} \ No newline at end of file diff --git a/source/mir/storage/StatementGenerator.java b/source/mir/storage/StatementGenerator.java new file mode 100755 index 00000000..51e0747a --- /dev/null +++ b/source/mir/storage/StatementGenerator.java @@ -0,0 +1,149 @@ +/* + * Copyright (C) 2005 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 mir.storage; + +import mir.log.LoggerWrapper; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +/** + * Base class for (sql) statement generators + */ +public class StatementGenerator { + private static LoggerWrapper logger = new LoggerWrapper("Database.Statements"); + + public StatementGenerator() { + query = new StringBuffer(); + parameters = new ArrayList(); + } + + protected void appendQuery(String aPart) { + query.append(aPart); + } + + protected void appendParameter(Object aParameter) { + parameters.add(aParameter); + } + + /** + * Executes the statement. Returns the number of modified records. + */ + protected int executeWithModifiedCount(Connection aConnection) throws DatabaseFailure { + long start = System.currentTimeMillis(); + + try { + aConnection.setAutoCommit(false); + logQueryBefore(query.toString()); + + PreparedStatement statement = aConnection.prepareStatement(query.toString()); + + int index = 1; + Iterator i = parameters.iterator(); + + while (i.hasNext()) { + statement.setObject(index, i.next()); + index++; + } + + int result = statement.executeUpdate(); + + logQueryAfter(query.toString(), System.currentTimeMillis() - start); + + return result; + } + catch (Throwable e) { + logQueryError(query.toString(), System.currentTimeMillis() - start, e); + System.out.println(e.toString()); + + throw new DatabaseFailure(e); + } + finally { + try { + aConnection.setAutoCommit(true); + } + catch (Exception e) { + } + } + } + + /** + * Executes the statement. Returns a resultset. + */ + protected ResultSet executeWithResultSet(Connection aConnection) throws DatabaseFailure { + long start = System.currentTimeMillis(); + + try { + logQueryBefore(query.toString()); + + PreparedStatement statement = aConnection.prepareStatement(query.toString()); + + int index = 1; + Iterator i = parameters.iterator(); + + while (i.hasNext()) { + statement.setObject(index, i.next()); + index++; + } + + ResultSet result = statement.executeQuery(); + + logQueryAfter(query.toString(), System.currentTimeMillis() - start); + + return result; + } + catch (Throwable e) { + logQueryError(query.toString(), System.currentTimeMillis() - start, e); + System.out.println(e.toString()); + + throw new DatabaseFailure(e); + } + } + + private void logQueryBefore(String aQuery) { + logger.debug("about to perform QUERY " + aQuery); + } + + private void logQueryAfter(String aQuery, long aTime) { + logger.info("QUERY " + aQuery + " took " + aTime + "ms."); + } + + private void logQueryError(String aQuery, long aTime, Throwable anException) { + logger.error("QUERY " + aQuery + " took " + aTime + "ms, but threw exception " + anException.toString()); + } + + + private StringBuffer query; + private List parameters; +} diff --git a/source/mir/util/xml/html/HTMLScanner.java b/source/mir/util/xml/html/HTMLScanner.java index dd8c9908..816c8fac 100755 --- a/source/mir/util/xml/html/HTMLScanner.java +++ b/source/mir/util/xml/html/HTMLScanner.java @@ -30,6 +30,7 @@ public class HTMLScanner { while (!reader.isAtEnd()) { char c = reader.peek(); + // TODO: << should result in the first < to be regarded as CDATA if (c != '<') readCData(); else { diff --git a/source/mircoders/abuse/FilterEngine.java b/source/mircoders/abuse/FilterEngine.java index 56c72168..e36e95f3 100755 --- a/source/mircoders/abuse/FilterEngine.java +++ b/source/mircoders/abuse/FilterEngine.java @@ -30,16 +30,6 @@ package mircoders.abuse; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.TimeZone; - import mir.config.MirPropertiesConfiguration; import mir.entity.Entity; import mir.entity.adapter.EntityAdapter; @@ -47,11 +37,14 @@ import mir.entity.adapter.EntityAdapterModel; import mir.entity.adapter.EntityIteratorAdapter; import mir.log.LoggerWrapper; import mir.session.Request; -import mir.storage.StorageObjectExc; +import mir.storage.DatabaseExc; import mircoders.global.MirGlobal; import mircoders.storage.DatabaseFilter; import mircoders.storage.DatabaseFilterGroup; +import java.text.SimpleDateFormat; +import java.util.*; + public class FilterEngine { private Map filterTypes; private List filterTypeIds; @@ -241,7 +234,7 @@ public class FilterEngine { public String createFilter(String aType, String anExpression, String aComments, String aTag, String anArticleAction, - String aCommentAction) throws StorageObjectExc { + String aCommentAction) throws DatabaseExc { FilterInstance instance; try { @@ -382,7 +375,7 @@ public class FilterEngine { filterGroup.getEntity().update(); } - public synchronized void addFilterGroup(String aName) throws StorageObjectExc { + public synchronized void addFilterGroup(String aName) throws DatabaseExc { Entity entity = DatabaseFilterGroup.getInstance().createNewEntity(); entity.setFieldValue("name", aName); entity.setFieldValue("priority", "1"); @@ -420,7 +413,7 @@ public class FilterEngine { String aComments, String aTag, String anArticleAction, - String aCommentAction) throws StorageObjectExc { + String aCommentAction) throws DatabaseExc { return getFilterGroupForId(aGroupId).createFilter(aType, anExpression, aComments, aTag, anArticleAction, aCommentAction); } diff --git a/source/mircoders/entity/EntityComment.java b/source/mircoders/entity/EntityComment.java index 9d9c064a..022ccfe4 100755 --- a/source/mircoders/entity/EntityComment.java +++ b/source/mircoders/entity/EntityComment.java @@ -33,15 +33,15 @@ package mircoders.entity; import java.util.Map; import mir.entity.AbstractEntity; -import mir.storage.StorageObjectFailure; +import mir.storage.DatabaseFailure; import mircoders.storage.DatabaseCommentToMedia; import mircoders.storage.DatabaseContent; /** * This class maps one line of the comment-table to a java-object. * - * @author $Author: rhindes $ - * @version $Revision: 1.16.2.5 $ $Date: 2005/02/10 16:22:32 $ + * @author $Author: zapata $ + * @version $Revision: 1.16.2.6 $ $Date: 2005/03/26 11:26:26 $ */ @@ -74,12 +74,8 @@ public class EntityComment extends AbstractEntity { /** * Deattaches media from a comment - * - * @param aCommentId - * @param aMediaId - * @throws StorageObjectFailure */ - public void dettach(String aCommentId,String aMediaId) throws StorageObjectFailure + public void dettach(String aCommentId,String aMediaId) throws DatabaseFailure { if (aMediaId!=null){ DatabaseCommentToMedia.getInstance().delete(aCommentId, aMediaId); @@ -88,12 +84,10 @@ public class EntityComment extends AbstractEntity { } /** - * - * @param aMediaId - * @throws StorageObjectFailure + * Attaches media to a comment */ - public void attach(String aMediaId) throws StorageObjectFailure + public void attach(String aMediaId) throws DatabaseFailure { if (aMediaId!=null) { DatabaseCommentToMedia.getInstance().addMedia(getId(), aMediaId); diff --git a/source/mircoders/entity/EntityContent.java b/source/mircoders/entity/EntityContent.java index 51fbd2a0..d35ad7c7 100755 --- a/source/mircoders/entity/EntityContent.java +++ b/source/mircoders/entity/EntityContent.java @@ -37,14 +37,14 @@ import java.util.Map; import mir.entity.AbstractEntity; import mir.log.LoggerWrapper; -import mir.storage.StorageObjectFailure; +import mir.storage.DatabaseFailure; import mircoders.storage.DatabaseContentToMedia; /** * this class implements mapping of one line of the database table content * to a java object * - * @version $Id: EntityContent.java,v 1.19.2.10 2005/02/10 16:22:32 rhindes Exp $ + * @version $Id: EntityContent.java,v 1.19.2.11 2005/03/26 11:26:26 zapata Exp $ * @author mir-coders group * */ @@ -63,7 +63,7 @@ public class EntityContent extends AbstractEntity { /** * set is_produced flag for the article */ - public void setProduced(boolean yesno) throws StorageObjectFailure + public void setProduced(boolean yesno) throws DatabaseFailure { String value = (yesno) ? "1":"0"; if (value.equals( getFieldValue("is_produced") )) return; @@ -76,11 +76,11 @@ public class EntityContent extends AbstractEntity { stmt = con.createStatement(); database.executeUpdate(stmt,sql); } - catch (StorageObjectFailure e) { + catch (DatabaseFailure e) { throw e; } catch (SQLException e) { - throw new StorageObjectFailure(e); + throw new DatabaseFailure(e); } finally { database.freeConnection(con,stmt); @@ -92,9 +92,9 @@ public class EntityContent extends AbstractEntity { * * @param anArticleId * @param aMediaId - * @throws StorageObjectFailure + * @throws DatabaseFailure */ - public void dettach(String anArticleId, String aMediaId) throws StorageObjectFailure + public void dettach(String anArticleId, String aMediaId) throws DatabaseFailure { if (aMediaId!=null){ DatabaseContentToMedia.getInstance().delete(anArticleId, aMediaId); @@ -107,7 +107,7 @@ public class EntityContent extends AbstractEntity { * Attaches media to the article */ - public void attach(String aMediaId) throws StorageObjectFailure + public void attach(String aMediaId) throws DatabaseFailure { if (aMediaId!=null) { DatabaseContentToMedia.getInstance().addMedia(getId(),aMediaId); diff --git a/source/mircoders/entity/EntityImages.java b/source/mircoders/entity/EntityImages.java index 5fb1f1b7..360394c7 100755 --- a/source/mircoders/entity/EntityImages.java +++ b/source/mircoders/entity/EntityImages.java @@ -35,16 +35,10 @@ import java.io.InputStream; import java.sql.SQLException; import mir.log.LoggerWrapper; -import mir.storage.StorageObjectFailure; +import mir.storage.DatabaseFailure; import mir.util.StreamCopier; -import mircoders.media.ImageProcessor; - -/** - * - * @author RK, mh, mir-coders - * @version $Id: EntityImages.java,v 1.21.2.8 2005/02/10 16:22:32 rhindes Exp $ - */ - +import mir.media.image.ImageProcessor; +import mir.media.image.JAIImageProcessor; public class EntityImages extends EntityUploadedMedia { @@ -64,25 +58,25 @@ public class EntityImages extends EntityUploadedMedia /** * Retrieves the image data */ - public InputStream getImage() throws StorageObjectFailure { + public byte[] getImage() throws DatabaseFailure { try { return database.getBinaryField("select image_data from images where id="+getId()); } catch (SQLException e) { - throw new StorageObjectFailure(e); + throw new DatabaseFailure(e); } } /** * Processes and saves image data */ - public void setImage(InputStream anInputStream, String type) throws StorageObjectFailure { + public void setImage(InputStream anInputStream, String type) throws DatabaseFailure { if (anInputStream != null) { try { ByteArrayOutputStream inputData = new ByteArrayOutputStream(); StreamCopier.copy(anInputStream, inputData); - ImageProcessor processor = new ImageProcessor(inputData.toByteArray()); + ImageProcessor processor = new JAIImageProcessor(inputData.toByteArray()); processor.descaleImage(maxImageSize, minDescaleRatio, minDescaleReduction); ByteArrayOutputStream imageData = new ByteArrayOutputStream(); @@ -103,7 +97,7 @@ public class EntityImages extends EntityUploadedMedia update(); } catch (Exception e) { - throw new StorageObjectFailure(e); + throw new DatabaseFailure(e); } } } @@ -114,12 +108,12 @@ public class EntityImages extends EntityUploadedMedia * * It will also take care of closing the OutputStream. */ - public InputStream getIcon() throws StorageObjectFailure { + public byte[] getIcon() throws DatabaseFailure { try { return database.getBinaryField("select icon_data from images where id="+getId()); } catch (SQLException e) { - throw new StorageObjectFailure(e); + throw new DatabaseFailure(e); } } } diff --git a/source/mircoders/entity/EntityUploadedMedia.java b/source/mircoders/entity/EntityUploadedMedia.java index 30ffb87a..74cb05ce 100755 --- a/source/mircoders/entity/EntityUploadedMedia.java +++ b/source/mircoders/entity/EntityUploadedMedia.java @@ -35,13 +35,13 @@ import java.util.Map; import mir.entity.AbstractEntity; import mir.entity.Entity; import mir.log.LoggerWrapper; -import mir.storage.StorageObjectFailure; +import mir.storage.DatabaseFailure; import mircoders.storage.DatabaseUploadedMedia; /** * * @author mh, mir-coders group - * @version $Id: EntityUploadedMedia.java,v 1.26.2.11 2005/02/10 16:22:32 rhindes Exp $ + * @version $Id: EntityUploadedMedia.java,v 1.26.2.12 2005/03/26 11:26:26 zapata Exp $ */ public class EntityUploadedMedia extends AbstractEntity { @@ -51,7 +51,7 @@ public class EntityUploadedMedia extends AbstractEntity { logger = new LoggerWrapper("Entity.UploadedMedia"); } - public void update() throws StorageObjectFailure { + public void update() throws DatabaseFailure { super.update(); try { @@ -74,7 +74,7 @@ public class EntityUploadedMedia extends AbstractEntity { ); } catch (SQLException e) { - throw new StorageObjectFailure(e); + throw new DatabaseFailure(e); } } @@ -92,13 +92,13 @@ public class EntityUploadedMedia extends AbstractEntity { * * @return mir.entity.Entity */ - public Entity getMediaType() throws StorageObjectFailure { + public Entity getMediaType() throws DatabaseFailure { Entity ent = null; try { ent = DatabaseUploadedMedia.getInstance().getMediaType(this); } - catch (StorageObjectFailure e) { - throw new StorageObjectFailure(e); + catch (DatabaseFailure e) { + throw new DatabaseFailure(e); } return ent; } diff --git a/source/mircoders/localizer/basic/MirBasicAdminInterfaceLocalizer.java b/source/mircoders/localizer/basic/MirBasicAdminInterfaceLocalizer.java index 727e3bb7..da30fb26 100755 --- a/source/mircoders/localizer/basic/MirBasicAdminInterfaceLocalizer.java +++ b/source/mircoders/localizer/basic/MirBasicAdminInterfaceLocalizer.java @@ -51,7 +51,7 @@ import mir.generator.GeneratorExc; import mir.log.LoggerWrapper; import mir.misc.StringUtil; import mir.module.ModuleExc; -import mir.storage.StorageObjectFailure; +import mir.storage.DatabaseFailure; import mir.util.DateTimeFunctions; import mir.util.EntityUtility; import mir.util.StringRoutines; @@ -80,7 +80,6 @@ public class MirBasicAdminInterfaceLocalizer implements MirAdminInterfaceLocaliz protected MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance(); public MirBasicAdminInterfaceLocalizer() throws MirLocalizerFailure { - simpleCommentOperations = new ArrayList(); simpleArticleOperations = new ArrayList(); simpleCommentOperationsMap = new HashMap(); @@ -167,9 +166,12 @@ public class MirBasicAdminInterfaceLocalizer implements MirAdminInterfaceLocaliz /** {@inheritDoc} */ public String makePasswordDigest(String aPassword) { + + return aPassword; } + /** {@inheritDoc} */ public void initializeArticle(Map anArticle) { anArticle.put("is_published", "0"); anArticle.put("date", StringUtil.date2webdbDate(new GregorianCalendar())); @@ -271,7 +273,7 @@ public class MirBasicAdminInterfaceLocalizer implements MirAdminInterfaceLocaliz } } - protected abstract boolean isAvailable(Entity anEntity) throws StorageObjectFailure ; + protected abstract boolean isAvailable(Entity anEntity) throws DatabaseFailure ; protected abstract void performModification(EntityAdapter aUser, Entity anEntity) throws MirLocalizerExc, MirLocalizerFailure ; } @@ -284,17 +286,17 @@ public class MirBasicAdminInterfaceLocalizer implements MirAdminInterfaceLocaliz this(aName, true); } - protected boolean isAvailable(Entity anEntity) throws StorageObjectFailure { + protected boolean isAvailable(Entity anEntity) throws DatabaseFailure { return anEntity instanceof EntityComment && isAvailable((EntityComment) anEntity); } - protected void performModification(EntityAdapter aUser, Entity anEntity) throws StorageObjectFailure { + protected void performModification(EntityAdapter aUser, Entity anEntity) throws DatabaseFailure { performModification(aUser, (EntityComment) anEntity); DatabaseContent.getInstance().setUnproduced("id="+anEntity.getFieldValue("to_media")); } - protected abstract boolean isAvailable(EntityComment aComment) throws StorageObjectFailure ; - protected abstract void performModification(EntityAdapter aUser, EntityComment aComment) throws StorageObjectFailure ; + protected abstract boolean isAvailable(EntityComment aComment) throws DatabaseFailure ; + protected abstract void performModification(EntityAdapter aUser, EntityComment aComment) throws DatabaseFailure ; } public static abstract class ArticleModifyingOperation extends EntityModifyingOperation { @@ -302,17 +304,17 @@ public class MirBasicAdminInterfaceLocalizer implements MirAdminInterfaceLocaliz super(aName, aLogOperation); } - protected boolean isAvailable(Entity anEntity) throws StorageObjectFailure { + protected boolean isAvailable(Entity anEntity) throws DatabaseFailure { return anEntity instanceof EntityContent && isAvailable((EntityContent) anEntity); } - protected void performModification(EntityAdapter aUser, Entity anEntity) throws StorageObjectFailure { + protected void performModification(EntityAdapter aUser, Entity anEntity) throws DatabaseFailure { performModification(aUser, (EntityContent) anEntity); anEntity.setFieldValue("is_produced", "0"); } - protected abstract boolean isAvailable(EntityContent anArticle) throws StorageObjectFailure ; - protected abstract void performModification(EntityAdapter aUser, EntityContent anArticle) throws StorageObjectFailure ; + protected abstract boolean isAvailable(EntityContent anArticle) throws DatabaseFailure ; + protected abstract void performModification(EntityAdapter aUser, EntityContent anArticle) throws DatabaseFailure ; } protected static class SetCommentFieldOperation extends CommentModifyingOperation { @@ -330,7 +332,7 @@ public class MirBasicAdminInterfaceLocalizer implements MirAdminInterfaceLocaliz return true; } - protected void performModification(EntityAdapter aUser, EntityComment aComment) throws StorageObjectFailure { + protected void performModification(EntityAdapter aUser, EntityComment aComment) throws DatabaseFailure { aComment.setFieldValue(field, value); } } @@ -351,7 +353,7 @@ public class MirBasicAdminInterfaceLocalizer implements MirAdminInterfaceLocaliz return true; } - protected void performModification(EntityAdapter aUser, EntityComment aComment) throws StorageObjectFailure { + protected void performModification(EntityAdapter aUser, EntityComment aComment) throws DatabaseFailure { Iterator i = values.entrySet().iterator(); while (i.hasNext()) { @@ -377,7 +379,7 @@ public class MirBasicAdminInterfaceLocalizer implements MirAdminInterfaceLocaliz return aComment.getFieldValue(field) == null || !aComment.getFieldValue(field).equals(value); } - protected void performModification(EntityAdapter aUser, EntityComment aComment) throws StorageObjectFailure { + protected void performModification(EntityAdapter aUser, EntityComment aComment) throws DatabaseFailure { aComment.setFieldValue(field, value); } } @@ -397,7 +399,7 @@ public class MirBasicAdminInterfaceLocalizer implements MirAdminInterfaceLocaliz return true; } - protected void performModification(EntityAdapter aUser, EntityContent anArticle) throws StorageObjectFailure { + protected void performModification(EntityAdapter aUser, EntityContent anArticle) throws DatabaseFailure { anArticle.setFieldValue(field, value); } } @@ -417,7 +419,7 @@ public class MirBasicAdminInterfaceLocalizer implements MirAdminInterfaceLocaliz return anArticle.getFieldValue(field) == null || !anArticle.getFieldValue(field).equals(value); } - protected void performModification(EntityAdapter aUser, EntityContent anArticle) throws StorageObjectFailure { + protected void performModification(EntityAdapter aUser, EntityContent anArticle) throws DatabaseFailure { anArticle.setFieldValue(field, value); } } @@ -442,7 +444,7 @@ public class MirBasicAdminInterfaceLocalizer implements MirAdminInterfaceLocaliz return anArticle.getFieldValue(field) != null && oldValues.contains(anArticle.getFieldValue(field)); } - protected void performModification(EntityAdapter aUser, EntityContent anArticle) throws StorageObjectFailure { + protected void performModification(EntityAdapter aUser, EntityContent anArticle) throws DatabaseFailure { anArticle.setFieldValue(field, newValue); } } diff --git a/source/mircoders/media/MediaHandlerImages.java b/source/mircoders/media/MediaHandlerImages.java index 4bf2f8f4..d4087e3e 100755 --- a/source/mircoders/media/MediaHandlerImages.java +++ b/source/mircoders/media/MediaHandlerImages.java @@ -29,10 +29,7 @@ */ package mircoders.media; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; +import java.io.*; import mir.config.MirPropertiesConfiguration; import mir.entity.Entity; @@ -60,7 +57,7 @@ import mircoders.entity.EntityImages; * * @see mir.media.MediaHandler * @author mh - * @version $Id: MediaHandlerImages.java,v 1.23.2.7 2005/01/23 15:36:04 zapata Exp $ + * @version $Id: MediaHandlerImages.java,v 1.23.2.8 2005/03/26 11:26:26 zapata Exp $ */ @@ -78,18 +75,14 @@ public abstract class MediaHandlerImages extends AbstractMediaHandler implements } public InputStream getMedia(Entity ent, Entity mediaTypeEnt) throws MediaExc, MediaFailure { - InputStream inputStream; - try { - inputStream = ((EntityImages) ent).getImage(); + return new ByteArrayInputStream(((EntityImages) ent).getImage()); } catch (Throwable e) { logger.error("MediaHandlerImages.getImage: " + e.toString()); throw new MediaFailure(e); } - - return inputStream; } public void store(UploadedFile anUploadedFile, Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure { @@ -135,9 +128,10 @@ public abstract class MediaHandlerImages extends AbstractMediaHandler implements ent.getFieldValue("image_data")!= null) { // make icon try { - InputStream in = ((EntityImages) ent).getIcon(); + InputStream in = new ByteArrayInputStream(((EntityImages) ent).getIcon()); FileUtil.write(iconFilePath, in); - in = ((EntityImages)ent).getImage(); + + in = new ByteArrayInputStream(((EntityImages) ent).getImage()); FileUtil.write(productionFilePath, in); ent.setFieldValue("icon_path",getIconStoragePath()+filepath); ent.setFieldValue("publish_path",filepath); @@ -156,16 +150,13 @@ public abstract class MediaHandlerImages extends AbstractMediaHandler implements } public InputStream getThumbnail(Entity ent) throws MediaExc, MediaFailure { - InputStream in; try { - in = ((EntityImages) ent).getIcon(); + return new ByteArrayInputStream(((EntityImages) ent).getIcon()); } catch (Throwable e) { logger.error("MediaHandlerImages.getIcon: " + e.toString()); throw new MediaFailure(e); } - - return in; } public String getStoragePath() { diff --git a/source/mircoders/media/MediaHandlerImagesExtern.java b/source/mircoders/media/MediaHandlerImagesExtern.java index c3a2a898..2e001c7c 100755 --- a/source/mircoders/media/MediaHandlerImagesExtern.java +++ b/source/mircoders/media/MediaHandlerImagesExtern.java @@ -39,6 +39,8 @@ import mir.entity.Entity; import mir.log.LoggerWrapper; import mir.media.MediaExc; import mir.media.MediaFailure; +import mir.media.image.ImageProcessor; +import mir.media.image.JAIImageProcessor; import mir.misc.StringUtil; @@ -82,7 +84,7 @@ public class MediaHandlerImagesExtern extends MediaHandlerGeneric throw new MediaExc("error in MediaHandlerImagesExtern.produce(): " + filePath + " does not exist!"); } else { - ImageProcessor processor = new ImageProcessor(imageFile); + ImageProcessor processor = new JAIImageProcessor(imageFile); processor.descaleImage(maxIconSize, minDescaleRatio, minDescaleReduction); File dir = new File(iconFile.getParent()); diff --git a/source/mircoders/module/ModuleComment.java b/source/mircoders/module/ModuleComment.java index e64ea243..4cceb56b 100755 --- a/source/mircoders/module/ModuleComment.java +++ b/source/mircoders/module/ModuleComment.java @@ -68,14 +68,6 @@ public class ModuleComment extends AbstractModule } } - /** - * - * @param theValues - * @return - * @throws ModuleExc - * @throws ModuleFailure - */ - public String set(Map theValues) throws ModuleExc, ModuleFailure { try { Entity theEntity = database.selectById((String)theValues.get("id")); diff --git a/source/mircoders/module/ModuleLanguage.java b/source/mircoders/module/ModuleLanguage.java index 9997ed6a..c8550589 100755 --- a/source/mircoders/module/ModuleLanguage.java +++ b/source/mircoders/module/ModuleLanguage.java @@ -38,15 +38,6 @@ import mir.module.ModuleFailure; import mir.util.JDBCStringRoutines; import mircoders.storage.DatabaseLanguage; -/** - * Title: mir - another content management system - * Description: - * Copyright: Copyright (c) 2001 - * Company: indymedia - * @author idefix - * @version 1.0 - */ - public class ModuleLanguage extends AbstractModule { static LoggerWrapper logger = new LoggerWrapper("Module.Language"); diff --git a/source/mircoders/module/ModuleMediaType.java b/source/mircoders/module/ModuleMediaType.java index dc82fefa..95e86c43 100755 --- a/source/mircoders/module/ModuleMediaType.java +++ b/source/mircoders/module/ModuleMediaType.java @@ -38,6 +38,7 @@ import mir.log.LoggerWrapper; import mir.module.AbstractModule; import mir.util.JDBCStringRoutines; import mir.util.StringRoutines; +import mir.storage.DatabaseExc; import mircoders.storage.DatabaseMediaType; public class ModuleMediaType extends AbstractModule { @@ -57,11 +58,16 @@ public class ModuleMediaType extends AbstractModule { EntityList mediaTypes; - mediaTypes = DatabaseMediaType.getInstance().selectByWhereClause("mime_type = '"+JDBCStringRoutines.escapeStringLiteral(aMimeType)+"'"); - if (mediaTypes.size() == 0) { - mediaTypes = DatabaseMediaType.getInstance().selectByWhereClause("mime_type = '"+JDBCStringRoutines.escapeStringLiteral(mimeTypeMajor+"/*")+"'"); + try { + mediaTypes = DatabaseMediaType.getInstance().selectByWhereClause("mime_type = '"+JDBCStringRoutines.escapeStringLiteral(aMimeType)+"'"); + if (mediaTypes.size() == 0) { + mediaTypes = DatabaseMediaType.getInstance().selectByWhereClause("mime_type = '"+JDBCStringRoutines.escapeStringLiteral(mimeTypeMajor+"/*")+"'"); + } + if (mediaTypes.size() == 0) { + return null; + } } - if (mediaTypes.size() == 0) { + catch (DatabaseExc e) { return null; } @@ -69,7 +75,14 @@ public class ModuleMediaType extends AbstractModule { } public Entity findMediaTypeForExtension(String anExtension) { - EntityList mediaTypes = DatabaseMediaType.getInstance().selectByWhereClause("name = '"+JDBCStringRoutines.escapeStringLiteral(anExtension)+"'"); + EntityList mediaTypes; + + try { + mediaTypes = DatabaseMediaType.getInstance().selectByWhereClause("name = '"+JDBCStringRoutines.escapeStringLiteral(anExtension)+"'"); + } + catch (DatabaseExc e) { + return null; + } if (mediaTypes.size() == 0) { return null; diff --git a/source/mircoders/module/ModuleUsers.java b/source/mircoders/module/ModuleUsers.java index 5aede0bf..23f42957 100755 --- a/source/mircoders/module/ModuleUsers.java +++ b/source/mircoders/module/ModuleUsers.java @@ -73,9 +73,10 @@ public class ModuleUsers extends AbstractModule try { String whereString = "login='" + JDBCStringRoutines.escapeStringLiteral(user) + "' " + - "and password='" + JDBCStringRoutines.escapeStringLiteral( - MirGlobal.localizer().adminInterface().makePasswordDigest(password)) + - "' " + + "and (" + + " password='" + JDBCStringRoutines.escapeStringLiteral(MirGlobal.localizer().adminInterface().makePasswordDigest(password)) + "'" + + " or password='" + JDBCStringRoutines.escapeStringLiteral(password) + "'" + + " )" + "and is_admin='1'"; EntityList userList = getByWhereClause(whereString, -1); @@ -140,13 +141,6 @@ public class ModuleUsers extends AbstractModule } } - /** - * - * @param theValues - * @return - * @throws ModuleExc - * @throws ModuleFailure - */ public String set (Map theValues) throws ModuleExc, ModuleFailure { try { return super.set(digestPassword(theValues)); diff --git a/source/mircoders/search/AudioSearchTerm.java b/source/mircoders/search/AudioSearchTerm.java index 1fc2fdc7..1f678471 100755 --- a/source/mircoders/search/AudioSearchTerm.java +++ b/source/mircoders/search/AudioSearchTerm.java @@ -39,7 +39,7 @@ import javax.servlet.http.HttpServletRequest; import mir.entity.Entity; import mir.entity.EntityBrowser; -import mir.storage.StorageObjectFailure; +import mir.storage.DatabaseFailure; import mircoders.storage.DatabaseAudio; import org.apache.lucene.document.Document; @@ -50,7 +50,7 @@ public class AudioSearchTerm extends SearchTerm{ super(null, "search_hasAudio", "hasAudio", null, "hasAudio"); } - public void index(Document doc, Entity entity) throws StorageObjectFailure{ + public void index(Document doc, Entity entity) throws DatabaseFailure{ // EntityList audio = DatabaseContentToMedia.getInstance().getAudio((EntityContent) entity); List extraTables = new ArrayList(); extraTables.add("content_x_media cxm"); diff --git a/source/mircoders/search/ImagesSearchTerm.java b/source/mircoders/search/ImagesSearchTerm.java index c509060b..ee404eca 100755 --- a/source/mircoders/search/ImagesSearchTerm.java +++ b/source/mircoders/search/ImagesSearchTerm.java @@ -40,7 +40,7 @@ import javax.servlet.http.HttpServletRequest; import mir.entity.Entity; import mir.entity.EntityBrowser; -import mir.storage.StorageObjectFailure; +import mir.storage.DatabaseFailure; import mircoders.entity.EntityImages; import mircoders.storage.DatabaseImages; @@ -53,7 +53,7 @@ public class ImagesSearchTerm extends SearchTerm{ super (null, "search_hasImages", "hasImages", "images", "images"); } - public void index(Document doc, Entity entity) throws StorageObjectFailure{ + public void index(Document doc, Entity entity) throws DatabaseFailure{ List extraTables = new ArrayList(); extraTables.add("content_x_media cxm"); diff --git a/source/mircoders/search/MediaSearchTerm.java b/source/mircoders/search/MediaSearchTerm.java index 7ac26962..e2f45610 100755 --- a/source/mircoders/search/MediaSearchTerm.java +++ b/source/mircoders/search/MediaSearchTerm.java @@ -35,7 +35,7 @@ import java.util.Map; import javax.servlet.http.HttpServletRequest; import mir.entity.Entity; -import mir.storage.StorageObjectFailure; +import mir.storage.DatabaseFailure; import org.apache.lucene.document.Document; @@ -45,7 +45,7 @@ public class MediaSearchTerm extends SearchTerm{ super(null, "search_hasMedia", "", null, ""); } - public void index(Document doc, Entity entity) throws StorageObjectFailure{ + public void index(Document doc, Entity entity) throws DatabaseFailure{ // only use this term for doing alternate queries on media return; } diff --git a/source/mircoders/search/TopicMatrixSearchTerm.java b/source/mircoders/search/TopicMatrixSearchTerm.java index 1d41b659..065b4763 100755 --- a/source/mircoders/search/TopicMatrixSearchTerm.java +++ b/source/mircoders/search/TopicMatrixSearchTerm.java @@ -35,7 +35,7 @@ import javax.servlet.http.HttpServletRequest; import mir.entity.Entity; import mir.entity.EntityList; -import mir.storage.StorageObjectFailure; +import mir.storage.DatabaseFailure; import mircoders.entity.EntityContent; import mircoders.storage.DatabaseContentToTopics; @@ -48,7 +48,7 @@ public class TopicMatrixSearchTerm extends SearchTerm{ super(null, "search_topicmatrix", "topic", null, null); } - public void index(Document doc, Entity entity) throws StorageObjectFailure{ + public void index(Document doc, Entity entity) throws DatabaseFailure{ EntityList topics = DatabaseContentToTopics.getInstance().getTopics((EntityContent) entity); if (topics != null && topics.size()>0){ for(int k=0;k0){ for(int k=0;k=anOffset+nrEntitiesPerListPage) { + if (commentList.size()>=nrEntitiesPerListPage) { urlBuilder.setValue("offset", anOffset + nrEntitiesPerListPage); responseData.put("nexturl" , urlBuilder.getQuery()); } @@ -302,8 +290,7 @@ public class ServletModuleComment extends ServletModule responseData.put("comments", commentList); responseData.put("from" , Integer.toString(anOffset+1)); - responseData.put("count", Integer.toString(count)); - responseData.put("to", Integer.toString(Math.min(anOffset+nrEntitiesPerListPage, count))); + responseData.put("to", Integer.toString(anOffset+commentList.size()-1)); ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator); } diff --git a/source/mircoders/servlet/ServletModuleContent.java b/source/mircoders/servlet/ServletModuleContent.java index d2a56d44..d09fd7f7 100755 --- a/source/mircoders/servlet/ServletModuleContent.java +++ b/source/mircoders/servlet/ServletModuleContent.java @@ -45,6 +45,7 @@ import javax.servlet.http.HttpServletResponse; import mir.entity.adapter.EntityAdapter; import mir.entity.adapter.EntityAdapterModel; import mir.entity.adapter.EntityIteratorAdapter; +import mir.entity.adapter.EntityAdapterEngine; import mir.generator.Generator; import mir.log.LoggerWrapper; import mir.misc.StringUtil; @@ -67,8 +68,7 @@ import mircoders.storage.DatabaseContentToTopics; * Article admin interface code */ -public class ServletModuleContent extends ServletModule -{ +public class ServletModuleContent extends ServletModule { private static ServletModuleContent instance = new ServletModuleContent(); public static ServletModule getInstance() { return instance; } private static ModuleContent contentModule; @@ -185,7 +185,6 @@ public class ServletModuleContent extends ServletModule /** * Attaches media to an article - * */ public void attach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { String mediaIdParam = aRequest.getParameter("mid"); @@ -407,9 +406,7 @@ public class ServletModuleContent extends ServletModule categoryMap.put("key", "topic"); categoryMap.put("listtype", "0"); categoryMap.put("listparameter", "3"); - categoryMap.put("items", - new EntityIteratorAdapter("", "title", - 20, MirGlobal.localizer().dataModel().adapterModel(), "topic")); + categoryMap.put("items", EntityAdapterEngine.retrieveAdapterList(model, "topic", "", "title", -1, 0)); topicsList.add(categoryMap); } else { @@ -417,6 +414,7 @@ public class ServletModuleContent extends ServletModule try { Map categoryMap = new HashMap(); List parts = StringRoutines.splitString(topicCategories[i], ":"); + String key = null; String listtype = "0"; String listparameter = "5"; @@ -438,9 +436,7 @@ public class ServletModuleContent extends ServletModule categoryMap.put("key", key); categoryMap.put("listtype", listtype); categoryMap.put("listparameter", listparameter); - categoryMap.put("items", - new EntityIteratorAdapter(where, order, - 20, MirGlobal.localizer().dataModel().adapterModel(), "topic")); + categoryMap.put("items", EntityAdapterEngine.retrieveAdapterList(model, "topic", where, order, -1, 0)); topicsList.add(categoryMap); } } diff --git a/source/mircoders/servlet/ServletModuleHidden.java b/source/mircoders/servlet/ServletModuleHidden.java index 2aa81ef8..47c16bf5 100755 --- a/source/mircoders/servlet/ServletModuleHidden.java +++ b/source/mircoders/servlet/ServletModuleHidden.java @@ -29,34 +29,29 @@ */ package mircoders.servlet; -import java.util.Iterator; -import java.util.Locale; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import mir.entity.adapter.EntityIteratorAdapter; +import mir.entity.adapter.EntityAdapterEngine; import mir.log.LoggerWrapper; import mir.servlet.ServletModule; import mir.servlet.ServletModuleExc; import mir.servlet.ServletModuleFailure; -import mir.storage.StorageObjectFailure; -import mir.util.CachingRewindableIterator; +import mir.storage.DatabaseFailure; import mir.util.HTTPRequestParser; import mir.util.JDBCStringRoutines; -import mircoders.global.MirGlobal; import mircoders.module.ModuleContent; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.List; +import java.util.Locale; +import java.util.Map; + /* * ServletModuleHidden - output of so called "censored" articles * @author mh * @version $Id - * */ -public class ServletModuleHidden extends ServletModule -{ +public class ServletModuleHidden extends ServletModule { private static ServletModuleHidden instance = new ServletModuleHidden(); public static ServletModule getInstance() { return instance; } @@ -68,15 +63,13 @@ public class ServletModuleHidden extends ServletModule try { mainModule = new ModuleContent(); } - catch (StorageObjectFailure e) { + catch (DatabaseFailure e) { logger.error("initialization of servletmoduleHidden failed: " + e.getMessage()); } } - public void list(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc - { -// determine parameter + public void list(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc { HTTPRequestParser requestParser = new HTTPRequestParser(req); Map responseData = ServletHelper.makeGenerationData(req, res, new Locale[] { getLocale(req), getFallbackLocale(req)}); @@ -88,11 +81,8 @@ public class ServletModuleHidden extends ServletModule String whereClause = "is_published=false AND webdb_create LIKE "+ "'"+JDBCStringRoutines.escapeStringLiteral(query_year)+"-"+JDBCStringRoutines.escapeStringLiteral(query_month)+"%'"; - Iterator articleList = - new CachingRewindableIterator( - new EntityIteratorAdapter( whereClause, "webdb_create", 100, - MirGlobal.localizer().dataModel().adapterModel(), "content", -1, 0) - ); + + List articleList = EntityAdapterEngine.retrieveAdapterList(model, definition, whereClause, "webdb_create", -1, 0); responseData.put("year", query_year); responseData.put("month", query_month); diff --git a/source/mircoders/servlet/ServletModuleOpenIndy.java b/source/mircoders/servlet/ServletModuleOpenIndy.java index 3470948e..0b54e64d 100755 --- a/source/mircoders/servlet/ServletModuleOpenIndy.java +++ b/source/mircoders/servlet/ServletModuleOpenIndy.java @@ -70,7 +70,7 @@ import mir.session.Session; import mir.session.SessionHandler; import mir.session.SimpleResponse; import mir.session.UploadedFile; -import mir.storage.StorageObjectFailure; +import mir.storage.DatabaseFailure; import mir.util.ExceptionFunctions; import mir.util.FileFunctions; import mir.util.HTTPParsedRequest; @@ -121,7 +121,7 @@ import org.apache.lucene.search.Searcher; * open-postings to the newswire * * @author mir-coders group - * @version $Id: ServletModuleOpenIndy.java,v 1.89.2.16 2005/03/10 19:12:53 john Exp $ + * @version $Id: ServletModuleOpenIndy.java,v 1.89.2.17 2005/03/26 11:26:27 zapata Exp $ * */ @@ -164,7 +164,7 @@ public class ServletModuleOpenIndy extends ServletModule contentModule = new ModuleContent(); defaultAction = "defaultAction"; } - catch (StorageObjectFailure e) { + catch (DatabaseFailure e) { logger.error("servletmoduleopenindy could not be initialized: " + e.getMessage()); } } diff --git a/source/mircoders/servlet/ServletModuleUploadedMedia.java b/source/mircoders/servlet/ServletModuleUploadedMedia.java index a1729e25..0f42987e 100755 --- a/source/mircoders/servlet/ServletModuleUploadedMedia.java +++ b/source/mircoders/servlet/ServletModuleUploadedMedia.java @@ -30,24 +30,10 @@ package mircoders.servlet; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import javax.servlet.ServletContext; -import javax.servlet.ServletOutputStream; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - import mir.config.MirPropertiesConfiguration; import mir.entity.Entity; import mir.entity.adapter.EntityAdapter; -import mir.entity.adapter.EntityAdapterModel; -import mir.entity.adapter.EntityIteratorAdapter; +import mir.entity.adapter.EntityAdapterEngine; import mir.log.LoggerWrapper; import mir.media.MediaHandler; import mir.servlet.ServletModule; @@ -55,25 +41,24 @@ import mir.servlet.ServletModuleExc; import mir.servlet.ServletModuleFailure; import mir.servlet.ServletModuleUserExc; import mir.session.UploadedFile; -import mir.util.CachingRewindableIterator; -import mir.util.ExceptionFunctions; -import mir.util.HTTPParsedRequest; -import mir.util.HTTPRequestParser; -import mir.util.JDBCStringRoutines; -import mir.util.SQLQueryBuilder; -import mir.util.URLBuilder; +import mir.util.*; import mircoders.entity.EntityComment; import mircoders.entity.EntityContent; import mircoders.entity.EntityUploadedMedia; -import mircoders.global.MirGlobal; import mircoders.media.MediaHelper; import mircoders.media.MediaUploadProcessor; import mircoders.media.UnsupportedMediaTypeExc; import mircoders.storage.DatabaseComment; import mircoders.storage.DatabaseContent; - import org.apache.commons.fileupload.FileItem; +import javax.servlet.ServletContext; +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.InputStream; +import java.util.*; + /** * *

Title:

@@ -100,6 +85,7 @@ public abstract class ServletModuleUploadedMedia extends ServletModule { public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc { + try { HTTPParsedRequest parsedRequest = new HTTPParsedRequest(aRequest, configuration.getString("Mir.DefaultEncoding"), @@ -136,7 +122,7 @@ public abstract class ServletModuleUploadedMedia extends ServletModule { if (articleid!=null) { EntityContent entContent = (EntityContent) DatabaseContent.getInstance().selectById(articleid); - i=mediaList.iterator(); + i = mediaList.iterator(); while (i.hasNext()) { String id = ((EntityUploadedMedia) i.next()).getId(); @@ -171,7 +157,7 @@ public abstract class ServletModuleUploadedMedia extends ServletModule { logAdminUsage(aRequest, "", mediaList.size() + " objects added"); - returnUploadedMediaList(aRequest, aResponse, mediaList, 1, mediaList.size(), mediaList.size(), "", null, null); + returnUploadedMediaList(aRequest, aResponse, mediaList, 1, mediaList.size(), "", null, null); } catch (Throwable t) { Throwable cause = ExceptionFunctions.traceCauseException(t); @@ -218,7 +204,7 @@ public abstract class ServletModuleUploadedMedia extends ServletModule { } public void returnUploadedMediaList(HttpServletRequest aRequest, HttpServletResponse aResponse, - Object aList, int aFrom, int aTo, int aCount, + Object aList, int aFrom, int aTo, String aThisUrl, String aNextUrl, String aPreviousUrl) throws ServletModuleExc { try { @@ -239,7 +225,6 @@ public abstract class ServletModuleUploadedMedia extends ServletModule { responseData.put("from", Integer.toString(aFrom)); - responseData.put("count", Integer.toString(aCount)); responseData.put("to", Integer.toString(aTo)); responseData.put("medialist", aList); @@ -257,23 +242,13 @@ public abstract class ServletModuleUploadedMedia extends ServletModule { HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); URLBuilder urlBuilder = new URLBuilder(); - EntityAdapterModel model; String nextPageUrl = null; String previousPageUrl = null; String thisUrl = null; - int count; - try { - model = MirGlobal.localizer().dataModel().adapterModel(); - - Object mediaList = - new CachingRewindableIterator( - new EntityIteratorAdapter(aWhereClause, anOrderByClause, nrEntitiesPerListPage, - model, definition, nrEntitiesPerListPage, anOffset) - ); - - count = mainModule.getSize(aWhereClause); + List list = + EntityAdapterEngine.retrieveAdapterList(model, definition, aWhereClause, anOrderByClause, nrEntitiesPerListPage, anOffset); urlBuilder.setValue("module", moduleName); urlBuilder.setValue("do", "list"); @@ -293,7 +268,7 @@ public abstract class ServletModuleUploadedMedia extends ServletModule { urlBuilder.setValue("offset", anOffset); thisUrl = urlBuilder.getQuery(); - if (count >= anOffset + nrEntitiesPerListPage) { + if (list.size() >= nrEntitiesPerListPage) { urlBuilder.setValue("offset", anOffset + nrEntitiesPerListPage); nextPageUrl = urlBuilder.getQuery(); } @@ -303,8 +278,8 @@ public abstract class ServletModuleUploadedMedia extends ServletModule { previousPageUrl = urlBuilder.getQuery(); } - returnUploadedMediaList(aRequest, aResponse, mediaList, - anOffset+1, anOffset+nrEntitiesPerListPage, count, thisUrl, + returnUploadedMediaList(aRequest, aResponse, list, + anOffset+1, anOffset+nrEntitiesPerListPage, thisUrl, nextPageUrl, previousPageUrl); } catch (Throwable e) { @@ -481,12 +456,6 @@ public abstract class ServletModuleUploadedMedia extends ServletModule { getThumbnail(aRequest, aResponse); } - /** - * - * @param aRequest - * @param aResponse - * @throws ServletModuleExc - */ public void getThumbnail(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { String id = aRequest.getParameter("id"); @@ -528,16 +497,14 @@ public abstract class ServletModuleUploadedMedia extends ServletModule { protected void addExtraData(Map aTarget) throws ServletModuleExc, ServletModuleFailure { try { - aTarget.put("mediafolders", - new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "mediaFolder")); + aTarget.put("mediafolders", EntityAdapterEngine.retrieveAdapterList(model, "mediaFolder", "", "", -1, 0)); } catch (Throwable t) { throw new ServletModuleFailure(t); } } - public void showarticles(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { + public void showarticles(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { String idParam = aRequest.getParameter("id"); if (idParam!=null && !idParam.equals("")) { try { diff --git a/source/mircoders/servlet/ServletModuleUsers.java b/source/mircoders/servlet/ServletModuleUsers.java index ae3f66f8..55993ee2 100755 --- a/source/mircoders/servlet/ServletModuleUsers.java +++ b/source/mircoders/servlet/ServletModuleUsers.java @@ -30,23 +30,13 @@ package mircoders.servlet; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - +import mir.entity.adapter.EntityAdapterEngine; import mir.entity.adapter.EntityAdapterModel; -import mir.entity.adapter.EntityIteratorAdapter; import mir.log.LoggerWrapper; import mir.servlet.ServletModule; import mir.servlet.ServletModuleExc; import mir.servlet.ServletModuleFailure; import mir.servlet.ServletModuleUserExc; -import mir.util.CachingRewindableIterator; import mir.util.HTTPRequestParser; import mir.util.URLBuilder; import mircoders.entity.EntityUsers; @@ -54,6 +44,10 @@ import mircoders.global.MirGlobal; import mircoders.module.ModuleUsers; import mircoders.storage.DatabaseUsers; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.*; + /** * * @@ -248,23 +242,16 @@ public class ServletModuleUsers extends ServletModule int anOffset) throws ServletModuleExc { URLBuilder urlBuilder = new URLBuilder(); - int count; try { Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}); - model = MirGlobal.localizer().dataModel().adapterModel(); - Object userList = - new CachingRewindableIterator( - new EntityIteratorAdapter( "", "login", nrEntitiesPerListPage, - MirGlobal.localizer().dataModel().adapterModel(), "user", nrEntitiesPerListPage, anOffset) - ); + List list = + EntityAdapterEngine.retrieveAdapterList(model, definition, "", "login", nrEntitiesPerListPage, anOffset); responseData.put("nexturl", null); responseData.put("prevurl", null); - count=mainModule.getSize(""); - urlBuilder.setValue("module", "Users"); urlBuilder.setValue("do", "list"); @@ -272,7 +259,7 @@ public class ServletModuleUsers extends ServletModule responseData.put("offset" , new Integer(anOffset).toString()); responseData.put("thisurl" , urlBuilder.getQuery()); - if (count>=anOffset+nrEntitiesPerListPage) { + if (list.size()>=nrEntitiesPerListPage) { urlBuilder.setValue("offset", (anOffset + nrEntitiesPerListPage)); responseData.put("nexturl" , urlBuilder.getQuery()); } @@ -282,14 +269,13 @@ public class ServletModuleUsers extends ServletModule responseData.put("prevurl" , urlBuilder.getQuery()); } - responseData.put("users", userList); + responseData.put("users", list); responseData.put("mayDeleteUsers", new Boolean(MirGlobal.accessControl().user().mayDeleteUsers(ServletHelper.getUser(aRequest)))); responseData.put("mayAddUsers", new Boolean(MirGlobal.accessControl().user().mayAddUsers(ServletHelper.getUser(aRequest)))); responseData.put("mayEditUsers", new Boolean(MirGlobal.accessControl().user().mayEditUsers(ServletHelper.getUser(aRequest)))); responseData.put("from" , Integer.toString(anOffset+1)); - responseData.put("count", Integer.toString(count)); - responseData.put("to", Integer.toString(Math.min(anOffset+nrEntitiesPerListPage, count))); + responseData.put("to", Integer.toString(anOffset+list.size())); responseData.put("offset" , Integer.toString(anOffset)); ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator); diff --git a/source/mircoders/storage/DatabaseArticleType.java b/source/mircoders/storage/DatabaseArticleType.java index 0b36989f..0091e0a7 100755 --- a/source/mircoders/storage/DatabaseArticleType.java +++ b/source/mircoders/storage/DatabaseArticleType.java @@ -30,31 +30,22 @@ package mircoders.storage; -/** - * Title: - * Description: - * Copyright: Copyright (c) 2001 - * Company: Indymedia - * @author - * @version 1.0 - */ - import mir.log.LoggerWrapper; import mir.storage.Database; -import mir.storage.StorageObjectFailure; +import mir.storage.DatabaseFailure; public class DatabaseArticleType extends Database { private static DatabaseArticleType instance; - public synchronized static DatabaseArticleType getInstance() throws StorageObjectFailure { + public synchronized static DatabaseArticleType getInstance() throws DatabaseFailure { if (instance == null) { instance = new DatabaseArticleType(); } return instance; } - private DatabaseArticleType() throws StorageObjectFailure { + private DatabaseArticleType() throws DatabaseFailure { super(); logger = new LoggerWrapper("Database.ArticleType"); diff --git a/source/mircoders/storage/DatabaseAudio.java b/source/mircoders/storage/DatabaseAudio.java index 68b25e4b..0f7ce741 100755 --- a/source/mircoders/storage/DatabaseAudio.java +++ b/source/mircoders/storage/DatabaseAudio.java @@ -35,7 +35,7 @@ import mir.entity.Entity; import mir.log.LoggerWrapper; import mir.misc.StringUtil; import mir.storage.Database; -import mir.storage.StorageObjectFailure; +import mir.storage.DatabaseFailure; public class DatabaseAudio extends Database { @@ -51,16 +51,16 @@ public class DatabaseAudio extends Database { return instance; } - private DatabaseAudio() throws StorageObjectFailure { + private DatabaseAudio() throws DatabaseFailure { super(); logger = new LoggerWrapper("Database.Audio"); mainTable = "audio"; - primaryKeySequence = "media_id_seq"; + entityClass = mircoders.entity.EntityAudio.class; } - public void update(Entity theEntity) throws StorageObjectFailure { + public void update(Entity theEntity) throws DatabaseFailure { String date = theEntity.getFieldValue("date"); if (date == null) { date = StringUtil.date2webdbDate(new GregorianCalendar()); @@ -70,7 +70,7 @@ public class DatabaseAudio extends Database { super.update(theEntity); } - public String insert(Entity theEntity) throws StorageObjectFailure { + public String insert(Entity theEntity) throws DatabaseFailure { String date = theEntity.getFieldValue("date"); if (date == null) { date = StringUtil.date2webdbDate(new GregorianCalendar()); @@ -79,4 +79,7 @@ public class DatabaseAudio extends Database { return super.insert(theEntity); } + protected String getPrimaryKeySequence() { + return "media_id_seq"; + } } diff --git a/source/mircoders/storage/DatabaseBreaking.java b/source/mircoders/storage/DatabaseBreaking.java index e058f508..aa476d58 100755 --- a/source/mircoders/storage/DatabaseBreaking.java +++ b/source/mircoders/storage/DatabaseBreaking.java @@ -32,25 +32,19 @@ package mircoders.storage; import mir.log.LoggerWrapper; import mir.storage.Database; -import mir.storage.StorageObjectFailure; - -/** - * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle - * - * - */ +import mir.storage.DatabaseFailure; public class DatabaseBreaking extends Database { private static DatabaseBreaking instance; - public synchronized static DatabaseBreaking getInstance() throws StorageObjectFailure { + public synchronized static DatabaseBreaking getInstance() throws DatabaseFailure { if (instance == null) { instance = new DatabaseBreaking(); } return instance; } - private DatabaseBreaking() throws StorageObjectFailure { + private DatabaseBreaking() throws DatabaseFailure { super(); logger = new LoggerWrapper("Database.Breaking"); diff --git a/source/mircoders/storage/DatabaseComment.java b/source/mircoders/storage/DatabaseComment.java index 12e8da1b..8561eb45 100755 --- a/source/mircoders/storage/DatabaseComment.java +++ b/source/mircoders/storage/DatabaseComment.java @@ -36,14 +36,7 @@ import java.sql.Statement; import mir.log.LoggerWrapper; import mir.storage.Database; -import mir.storage.StorageObjectFailure; - -/** - * This class implements the access to the comment-table for the - * media table. - * - * - */ +import mir.storage.DatabaseFailure; public class DatabaseComment extends Database { @@ -64,7 +57,7 @@ public class DatabaseComment extends Database { entityClass = mircoders.entity.EntityComment.class; } - public boolean deleteByContentId(String id) throws StorageObjectFailure { + public boolean deleteByContentId(String id) throws DatabaseFailure { Statement stmt = null; Connection con = null; String sql; @@ -79,7 +72,7 @@ public class DatabaseComment extends Database { stmt.executeUpdate(sql); } catch (SQLException sqe) { - new StorageObjectFailure(sqe); + new DatabaseFailure(sqe); return false; } finally { diff --git a/source/mircoders/storage/DatabaseCommentStatus.java b/source/mircoders/storage/DatabaseCommentStatus.java index 46bc65b0..01a7b463 100755 --- a/source/mircoders/storage/DatabaseCommentStatus.java +++ b/source/mircoders/storage/DatabaseCommentStatus.java @@ -32,13 +32,13 @@ package mircoders.storage; import mir.log.LoggerWrapper; import mir.storage.Database; -import mir.storage.StorageObjectFailure; +import mir.storage.DatabaseFailure; public class DatabaseCommentStatus extends Database { private static DatabaseCommentStatus instance; - public synchronized static DatabaseCommentStatus getInstance() throws StorageObjectFailure { + public synchronized static DatabaseCommentStatus getInstance() throws DatabaseFailure { if (instance == null) { instance = new DatabaseCommentStatus(); } @@ -46,7 +46,7 @@ public class DatabaseCommentStatus extends Database { return instance; } - private DatabaseCommentStatus() throws StorageObjectFailure { + private DatabaseCommentStatus() throws DatabaseFailure { super(); mainTable = "comment_status"; diff --git a/source/mircoders/storage/DatabaseCommentToMedia.java b/source/mircoders/storage/DatabaseCommentToMedia.java index 9f8807c4..8d6f0a12 100755 --- a/source/mircoders/storage/DatabaseCommentToMedia.java +++ b/source/mircoders/storage/DatabaseCommentToMedia.java @@ -37,17 +37,9 @@ import java.util.ArrayList; import mir.entity.EntityList; import mir.log.LoggerWrapper; import mir.storage.Database; -import mir.storage.StorageObjectFailure; +import mir.storage.DatabaseFailure; import mircoders.entity.EntityUploadedMedia; -/** - * implements abstract DB connection to the comment_x_media SQL table - * - * @author RK, mir-coders group - * @version $Id: DatabaseCommentToMedia.java,v 1.3.2.10 2005/02/10 16:22:22 rhindes Exp $ - * - */ - public class DatabaseCommentToMedia extends Database { private static DatabaseCommentToMedia instance; @@ -68,7 +60,7 @@ public class DatabaseCommentToMedia extends Database { } public void addMedia(String commentId, String mediaId) throws - StorageObjectFailure { + DatabaseFailure { if (commentId == null && mediaId == null) { return; } @@ -87,7 +79,7 @@ public class DatabaseCommentToMedia extends Database { } catch (Exception e) { logger.error("-- add media failed -- insert"); - throw new StorageObjectFailure("-- add media failed -- insert ", e); + throw new DatabaseFailure("-- add media failed -- insert ", e); } finally { freeConnection(con, stmt); @@ -95,7 +87,7 @@ public class DatabaseCommentToMedia extends Database { } public void setMedia(String commentId, String mediaId) throws - StorageObjectFailure { + DatabaseFailure { if (commentId == null && mediaId == null) { return; } @@ -112,7 +104,7 @@ public class DatabaseCommentToMedia extends Database { } catch (Exception e) { logger.error("-- set media failed -- delete"); - throw new StorageObjectFailure("-- set media failed -- delete ", e); + throw new DatabaseFailure("-- set media failed -- delete ", e); } finally { freeConnection(con, stmt); @@ -131,14 +123,14 @@ public class DatabaseCommentToMedia extends Database { } catch (Exception e) { logger.error("-- set media failed -- insert"); - throw new StorageObjectFailure("-- set media failed -- insert ", e); + throw new DatabaseFailure("-- set media failed -- insert ", e); } finally { freeConnection(con, stmt); } } - public void deleteByCommentId(String commentId) throws StorageObjectFailure { + public void deleteByCommentId(String commentId) throws DatabaseFailure { if (commentId == null) { //theLog.printDebugInfo("-- delete topics failed -- no comment id"); return; @@ -156,7 +148,7 @@ public class DatabaseCommentToMedia extends Database { } catch (Exception e) { logger.error("-- delete by commentId failed "); - throw new StorageObjectFailure( + throw new DatabaseFailure( "-- delete by comment id failed -- delete ", e); } finally { @@ -164,7 +156,7 @@ public class DatabaseCommentToMedia extends Database { } } - public void deleteByMediaId(String mediaId) throws StorageObjectFailure { + public void deleteByMediaId(String mediaId) throws DatabaseFailure { if (mediaId == null) { //theLog.printDebugInfo("-- delete topics failed -- no topic id"); return; @@ -183,7 +175,7 @@ public class DatabaseCommentToMedia extends Database { } catch (Exception e) { logger.error("-- delete media failed "); - throw new StorageObjectFailure("-- delete by media id failed -- ", e); + throw new DatabaseFailure("-- delete by media id failed -- ", e); } finally { freeConnection(con, stmt); @@ -191,7 +183,7 @@ public class DatabaseCommentToMedia extends Database { } public void delete(String commentId, String mediaId) throws - StorageObjectFailure { + DatabaseFailure { if (mediaId == null || commentId == null) { logger.debug("-- delete media failed -- missing parameter"); return; @@ -211,7 +203,7 @@ public class DatabaseCommentToMedia extends Database { } catch (Exception e) { logger.error("-- delete comment_x_media failed "); - throw new StorageObjectFailure("-- delete comment_x_media failed -- ", e); + throw new DatabaseFailure("-- delete comment_x_media failed -- ", e); } finally { freeConnection(con, stmt); @@ -219,7 +211,7 @@ public class DatabaseCommentToMedia extends Database { } public EntityList getComment(EntityUploadedMedia media) throws - StorageObjectFailure { + DatabaseFailure { EntityList returnList = null; if (media != null) { @@ -236,7 +228,7 @@ public class DatabaseCommentToMedia extends Database { } catch (Exception e) { logger.error("-- get comment failed"); - throw new StorageObjectFailure("-- get comment failed -- ", e); + throw new DatabaseFailure("-- get comment failed -- ", e); } } return returnList; @@ -247,7 +239,7 @@ public class DatabaseCommentToMedia extends Database { * a relation to a media */ - public EntityList getComment() throws StorageObjectFailure { + public EntityList getComment() throws DatabaseFailure { EntityList returnList = null; ArrayList extraTables = new ArrayList(); @@ -261,7 +253,7 @@ public class DatabaseCommentToMedia extends Database { } catch (Exception e) { logger.error("-- get comment failed"); - throw new StorageObjectFailure("-- get comment failed -- ", e); + throw new DatabaseFailure("-- get comment failed -- ", e); } return returnList; diff --git a/source/mircoders/storage/DatabaseContent.java b/source/mircoders/storage/DatabaseContent.java index cf0258fb..bf14742b 100755 --- a/source/mircoders/storage/DatabaseContent.java +++ b/source/mircoders/storage/DatabaseContent.java @@ -30,28 +30,17 @@ package mircoders.storage; -import java.sql.Connection; -import java.sql.Statement; - import mir.log.LoggerWrapper; import mir.storage.Database; -import mir.storage.StorageObjectFailure; +import mir.storage.DatabaseFailure; -/** - * this class implements the access to the content-table - * - * - */ +import java.sql.Connection; +import java.sql.Statement; public class DatabaseContent extends Database { private static DatabaseContent instance; - // Contructors / Singleton - - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo. - // see the "Singletons with needles and thread" article at JavaWorld -mh public synchronized static DatabaseContent getInstance() { if (instance == null ) { @@ -60,11 +49,10 @@ public class DatabaseContent extends Database { return instance; } - private DatabaseContent() throws StorageObjectFailure { + private DatabaseContent() throws DatabaseFailure { super(); mainTable="content"; - primaryKeySequence="media_id_seq"; logger = new LoggerWrapper("Database.Content"); entityClass = mircoders.entity.EntityContent.class; @@ -76,7 +64,7 @@ public class DatabaseContent extends Database { * sets the database flag is_produced to unproduced */ - public void setUnproduced(String where) throws StorageObjectFailure + public void setUnproduced(String where) throws DatabaseFailure { Connection con=null;Statement stmt=null; String sql = "update content set is_produced='0' where " + where; @@ -94,15 +82,7 @@ public class DatabaseContent extends Database { finally { freeConnection(con,stmt);} } - /** - * - * @param id - * @return - * @throws StorageObjectFailure - */ - - public boolean delete(String id) throws StorageObjectFailure - { + public boolean delete(String id) throws DatabaseFailure { DatabaseComment.getInstance().deleteByContentId(id); DatabaseContentToTopics.getInstance().deleteByContentId(id); DatabaseContentToMedia.getInstance().deleteByContentId(id); @@ -110,4 +90,7 @@ public class DatabaseContent extends Database { return super.delete(id); } + protected String getPrimaryKeySequence() { + return "media_id_seq"; + } } diff --git a/source/mircoders/storage/DatabaseContentToMedia.java b/source/mircoders/storage/DatabaseContentToMedia.java index bcdc80ec..11a2b357 100755 --- a/source/mircoders/storage/DatabaseContentToMedia.java +++ b/source/mircoders/storage/DatabaseContentToMedia.java @@ -37,14 +37,14 @@ import java.util.ArrayList; import mir.entity.EntityList; import mir.log.LoggerWrapper; import mir.storage.Database; -import mir.storage.StorageObjectFailure; +import mir.storage.DatabaseFailure; import mircoders.entity.EntityUploadedMedia; /** * implements abstract DB connection to the content_x_media SQL table * * @author RK, mir-coders group - * @version $Id: DatabaseContentToMedia.java,v 1.19.2.9 2005/02/10 16:22:22 rhindes Exp $ + * @version $Id: DatabaseContentToMedia.java,v 1.19.2.10 2005/03/26 11:26:28 zapata Exp $ * */ @@ -68,7 +68,7 @@ public class DatabaseContentToMedia extends Database { } public void addMedia(String contentId, String mediaId) throws - StorageObjectFailure { + DatabaseFailure { if (contentId == null && mediaId == null) { return; } @@ -87,7 +87,7 @@ public class DatabaseContentToMedia extends Database { } catch (Exception e) { logger.error("-- add media failed -- insert"); - throw new StorageObjectFailure("-- add media failed -- insert ", e); + throw new DatabaseFailure("-- add media failed -- insert ", e); } finally { freeConnection(con, stmt); @@ -95,7 +95,7 @@ public class DatabaseContentToMedia extends Database { } public void setMedia(String contentId, String mediaId) throws - StorageObjectFailure { + DatabaseFailure { if (contentId == null && mediaId == null) { return; } @@ -112,7 +112,7 @@ public class DatabaseContentToMedia extends Database { } catch (Exception e) { logger.error("-- set media failed -- delete"); - throw new StorageObjectFailure("-- set media failed -- delete ", e); + throw new DatabaseFailure("-- set media failed -- delete ", e); } finally { freeConnection(con, stmt); @@ -131,14 +131,14 @@ public class DatabaseContentToMedia extends Database { } catch (Exception e) { logger.error("-- set media failed -- insert"); - throw new StorageObjectFailure("-- set media failed -- insert ", e); + throw new DatabaseFailure("-- set media failed -- insert ", e); } finally { freeConnection(con, stmt); } } - public void deleteByContentId(String contentId) throws StorageObjectFailure { + public void deleteByContentId(String contentId) throws DatabaseFailure { if (contentId == null) { //theLog.printDebugInfo("-- delete topics failed -- no content id"); return; @@ -156,7 +156,7 @@ public class DatabaseContentToMedia extends Database { } catch (Exception e) { logger.error("-- delete by contentId failed "); - throw new StorageObjectFailure( + throw new DatabaseFailure( "-- delete by content id failed -- delete ", e); } finally { @@ -164,7 +164,7 @@ public class DatabaseContentToMedia extends Database { } } - public void deleteByMediaId(String mediaId) throws StorageObjectFailure { + public void deleteByMediaId(String mediaId) throws DatabaseFailure { if (mediaId == null) { //theLog.printDebugInfo("-- delete topics failed -- no topic id"); @@ -184,7 +184,7 @@ public class DatabaseContentToMedia extends Database { } catch (Exception e) { logger.error("-- delete media failed "); - throw new StorageObjectFailure("-- delete by media id failed -- ", e); + throw new DatabaseFailure("-- delete by media id failed -- ", e); } finally { freeConnection(con, stmt); @@ -192,7 +192,7 @@ public class DatabaseContentToMedia extends Database { } public void delete(String contentId, String mediaId) throws - StorageObjectFailure { + DatabaseFailure { if (mediaId == null || contentId == null) { logger.debug("-- delete media failed -- missing parameter"); return; @@ -212,7 +212,7 @@ public class DatabaseContentToMedia extends Database { } catch (Exception e) { logger.error("-- delete content_x_media failed "); - throw new StorageObjectFailure("-- delete content_x_media failed -- ", e); + throw new DatabaseFailure("-- delete content_x_media failed -- ", e); } finally { freeConnection(con, stmt); @@ -220,7 +220,7 @@ public class DatabaseContentToMedia extends Database { } public EntityList getContent(EntityUploadedMedia media) throws - StorageObjectFailure { + DatabaseFailure { EntityList returnList = null; if (media != null) { @@ -237,7 +237,7 @@ public class DatabaseContentToMedia extends Database { } catch (Exception e) { logger.error("-- get content failed"); - throw new StorageObjectFailure("-- get content failed -- ", e); + throw new DatabaseFailure("-- get content failed -- ", e); } } return returnList; @@ -247,7 +247,7 @@ public class DatabaseContentToMedia extends Database { * Returns a EntityList with all content-objects having a relation to a media */ - public EntityList getContent() throws StorageObjectFailure { + public EntityList getContent() throws DatabaseFailure { EntityList returnList = null; @@ -262,7 +262,7 @@ public class DatabaseContentToMedia extends Database { } catch (Exception e) { logger.error("-- get content failed"); - throw new StorageObjectFailure("-- get content failed -- ", e); + throw new DatabaseFailure("-- get content failed -- ", e); } return returnList; } diff --git a/source/mircoders/storage/DatabaseContentToTopics.java b/source/mircoders/storage/DatabaseContentToTopics.java index d3f55719..f1d4633b 100755 --- a/source/mircoders/storage/DatabaseContentToTopics.java +++ b/source/mircoders/storage/DatabaseContentToTopics.java @@ -30,6 +30,13 @@ package mircoders.storage; +import mir.entity.EntityList; +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.DatabaseFailure; +import mircoders.entity.EntityContent; +import mircoders.entity.EntityTopics; + import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; @@ -38,13 +45,6 @@ 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; - /** * This class implements the 1-n-relation between * content and topic @@ -96,7 +96,7 @@ public class DatabaseContentToTopics extends Database { * Returns a List of String-Objects from a content-id. */ public List getTopicsOfContent(String contentId) - throws StorageObjectFailure { + throws DatabaseFailure { ArrayList returnList = new ArrayList(); if (contentId != null) { @@ -137,14 +137,14 @@ public class DatabaseContentToTopics extends Database { return result; } - public void setTopics(String anArticleId, String [] aTopics) throws StorageObjectFailure { + public void setTopics(String anArticleId, String [] aTopics) throws DatabaseFailure { if (aTopics==null) setTopics(anArticleId, (List) null); else setTopics(anArticleId, Arrays.asList(aTopics)); } - public void setTopics(String anArticleId, List aTopics) throws StorageObjectFailure { + public void setTopics(String anArticleId, List aTopics) throws DatabaseFailure { List newTopics = new ArrayList(); if (aTopics!=null) { Iterator i = aTopics.iterator(); @@ -218,7 +218,7 @@ public class DatabaseContentToTopics extends Database { } public void deleteByContentId(String contentId) - throws StorageObjectFailure { + throws DatabaseFailure { if (contentId == null) { //theLog.printDebugInfo("-- delete topics failed -- no content id"); return; @@ -240,7 +240,7 @@ public class DatabaseContentToTopics extends Database { } public void deleteByTopicId(String topicId) - throws StorageObjectFailure { + throws DatabaseFailure { if (topicId == null) { //theLog.printDebugInfo("-- delete topics failed -- no topic id"); return; @@ -267,10 +267,10 @@ public class DatabaseContentToTopics extends Database { * Returns list of Content for a specific topic * @param topic * @return EntityList - * @throws StorageObjectFailure + * @throws DatabaseFailure */ public EntityList getContent(EntityTopics topic) - throws StorageObjectFailure { + throws DatabaseFailure { EntityList returnList=null; if (topic != null) { String id = topic.getId(); diff --git a/source/mircoders/storage/DatabaseFilter.java b/source/mircoders/storage/DatabaseFilter.java index 3a7fe733..ac2ee2c4 100755 --- a/source/mircoders/storage/DatabaseFilter.java +++ b/source/mircoders/storage/DatabaseFilter.java @@ -30,10 +30,6 @@ package mircoders.storage; -/** - * - */ - import mir.log.LoggerWrapper; import mir.storage.Database; diff --git a/source/mircoders/storage/DatabaseFilterGroup.java b/source/mircoders/storage/DatabaseFilterGroup.java index e91e7f5e..37de878b 100755 --- a/source/mircoders/storage/DatabaseFilterGroup.java +++ b/source/mircoders/storage/DatabaseFilterGroup.java @@ -30,10 +30,6 @@ package mircoders.storage; -/** - * - */ - import mir.log.LoggerWrapper; import mir.storage.Database; diff --git a/source/mircoders/storage/DatabaseImageColor.java b/source/mircoders/storage/DatabaseImageColor.java index 7b0ebda0..f4f6b085 100755 --- a/source/mircoders/storage/DatabaseImageColor.java +++ b/source/mircoders/storage/DatabaseImageColor.java @@ -33,12 +33,6 @@ package mircoders.storage; import mir.log.LoggerWrapper; import mir.storage.Database; -/** - * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle - * - * - */ - public class DatabaseImageColor extends Database { private static DatabaseImageColor instance; diff --git a/source/mircoders/storage/DatabaseImageFormat.java b/source/mircoders/storage/DatabaseImageFormat.java index 6a42f0d4..32e49303 100755 --- a/source/mircoders/storage/DatabaseImageFormat.java +++ b/source/mircoders/storage/DatabaseImageFormat.java @@ -33,12 +33,6 @@ package mircoders.storage; import mir.log.LoggerWrapper; import mir.storage.Database; -/** - * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle - * - * - */ - public class DatabaseImageFormat extends Database { private static DatabaseImageFormat instance; diff --git a/source/mircoders/storage/DatabaseImageLayout.java b/source/mircoders/storage/DatabaseImageLayout.java index 066db53e..8ed56d80 100755 --- a/source/mircoders/storage/DatabaseImageLayout.java +++ b/source/mircoders/storage/DatabaseImageLayout.java @@ -33,12 +33,6 @@ package mircoders.storage; import mir.log.LoggerWrapper; import mir.storage.Database; -/** - * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle - * - * - */ - public class DatabaseImageLayout extends Database { private static DatabaseImageLayout instance; diff --git a/source/mircoders/storage/DatabaseImageType.java b/source/mircoders/storage/DatabaseImageType.java index 78bd2f99..304d65f9 100755 --- a/source/mircoders/storage/DatabaseImageType.java +++ b/source/mircoders/storage/DatabaseImageType.java @@ -32,16 +32,6 @@ package mircoders.storage; import mir.log.LoggerWrapper; import mir.storage.Database; -/** - * - *

Title:

- *

Description:

- *

Copyright: Copyright (c) 2003

- *

Company:

- * @author not attributable - * @version 1.0 - */ - public class DatabaseImageType extends Database { private static DatabaseImageType instance; diff --git a/source/mircoders/storage/DatabaseImages.java b/source/mircoders/storage/DatabaseImages.java index 87ac2d82..2125d297 100755 --- a/source/mircoders/storage/DatabaseImages.java +++ b/source/mircoders/storage/DatabaseImages.java @@ -36,13 +36,7 @@ import mir.entity.Entity; import mir.log.LoggerWrapper; import mir.misc.StringUtil; import mir.storage.Database; -import mir.storage.StorageObjectFailure; - -/** - * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle - * - * - */ +import mir.storage.DatabaseFailure; public class DatabaseImages extends Database { @@ -61,11 +55,12 @@ public class DatabaseImages extends Database { logger = new LoggerWrapper("Database.Images"); mainTable = "images"; - primaryKeySequence = "media_id_seq"; entityClass = mircoders.entity.EntityImages.class; + markBinaryField("image_data"); + markBinaryField("icon_data"); } - public void update(Entity theEntity) throws StorageObjectFailure { + public void update(Entity theEntity) throws DatabaseFailure { String date = theEntity.getFieldValue("date"); if (date == null) { date = StringUtil.date2webdbDate(new GregorianCalendar()); @@ -75,7 +70,7 @@ public class DatabaseImages extends Database { super.update(theEntity); } - public String insert(Entity theEntity) throws StorageObjectFailure { + public String insert(Entity theEntity) throws DatabaseFailure { String date = theEntity.getFieldValue("date"); if (date == null) { @@ -85,4 +80,8 @@ public class DatabaseImages extends Database { return super.insert(theEntity); } + + protected String getPrimaryKeySequence() { + return "media_id_seq"; + } } diff --git a/source/mircoders/storage/DatabaseLanguage.java b/source/mircoders/storage/DatabaseLanguage.java index bb0eac8c..214d75fc 100755 --- a/source/mircoders/storage/DatabaseLanguage.java +++ b/source/mircoders/storage/DatabaseLanguage.java @@ -49,7 +49,7 @@ import mir.entity.Entity; import mir.entity.EntityBrowser; import mir.log.LoggerWrapper; import mir.storage.Database; -import mir.storage.StorageObjectFailure; +import mir.storage.DatabaseFailure; public class DatabaseLanguage extends Database { @@ -59,21 +59,21 @@ public class DatabaseLanguage extends Database { // could get preemted and we could end up with 2 instances of DatabaseFoo.. // see the "Singletons with needles and thread" article at JavaWorld -mh public synchronized static DatabaseLanguage getInstance() throws - StorageObjectFailure { + DatabaseFailure { if (instance == null) { instance = new DatabaseLanguage(); } return instance; } - private DatabaseLanguage() throws StorageObjectFailure { + private DatabaseLanguage() throws DatabaseFailure { super(); logger = new LoggerWrapper("Database.Language"); mainTable = "language"; } - public List getPopupData() throws StorageObjectFailure { + public List getPopupData() throws DatabaseFailure { List result = new ArrayList(); Iterator i = new EntityBrowser(this, "", "name", 100, -1, 0); diff --git a/source/mircoders/storage/DatabaseMediaType.java b/source/mircoders/storage/DatabaseMediaType.java index b8f3397e..0b983149 100755 --- a/source/mircoders/storage/DatabaseMediaType.java +++ b/source/mircoders/storage/DatabaseMediaType.java @@ -31,14 +31,7 @@ package mircoders.storage; import mir.log.LoggerWrapper; import mir.storage.Database; -import mir.storage.StorageObjectFailure; - -/** - * This class implements the access to the media_type-table for the - * media table. - * - * - */ +import mir.storage.DatabaseFailure; public class DatabaseMediaType extends Database { private static DatabaseMediaType instance; @@ -50,7 +43,7 @@ public class DatabaseMediaType extends Database { return instance; } - private DatabaseMediaType() throws StorageObjectFailure + private DatabaseMediaType() throws DatabaseFailure { super(); diff --git a/source/mircoders/storage/DatabaseMessages.java b/source/mircoders/storage/DatabaseMessages.java index 87e5bfd4..cb3b1ad7 100755 --- a/source/mircoders/storage/DatabaseMessages.java +++ b/source/mircoders/storage/DatabaseMessages.java @@ -33,17 +33,6 @@ package mircoders.storage; import mir.log.LoggerWrapper; import mir.storage.Database; - -/** - * Title: - * Description: - * Copyright: Copyright (c) 2001 - * Company: Indymedia - * @author - * @version 1.0 - */ - - public class DatabaseMessages extends Database { private static DatabaseMessages instance; diff --git a/source/mircoders/storage/DatabaseOther.java b/source/mircoders/storage/DatabaseOther.java index 6fe2936d..dd641f92 100755 --- a/source/mircoders/storage/DatabaseOther.java +++ b/source/mircoders/storage/DatabaseOther.java @@ -36,24 +36,11 @@ import mir.entity.Entity; import mir.log.LoggerWrapper; import mir.misc.StringUtil; import mir.storage.Database; -import mir.storage.StorageObjectFailure; - -/** - * - *

Title:

- *

Description:

- *

Copyright: Copyright (c) 2003

- *

Company:

- * @author not attributable - * @version 1.0 - */ +import mir.storage.DatabaseFailure; public class DatabaseOther extends Database { private static DatabaseOther instance; - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh public synchronized static DatabaseOther getInstance() { if (instance == null) { instance = new DatabaseOther(); @@ -66,11 +53,10 @@ public class DatabaseOther extends Database { logger = new LoggerWrapper("Database.OtherMedia"); mainTable = "other_media"; - primaryKeySequence = "media_id_seq"; entityClass = mircoders.entity.EntityOther.class; } - public void update(Entity theEntity) throws StorageObjectFailure { + public void update(Entity theEntity) throws DatabaseFailure { String date = theEntity.getFieldValue("date"); if (date == null) { date = StringUtil.date2webdbDate(new GregorianCalendar()); @@ -80,7 +66,7 @@ public class DatabaseOther extends Database { super.update(theEntity); } - public String insert(Entity theEntity) throws StorageObjectFailure { + public String insert(Entity theEntity) throws DatabaseFailure { String date = theEntity.getFieldValue("date"); if (date == null) { date = StringUtil.date2webdbDate(new GregorianCalendar()); @@ -89,6 +75,7 @@ public class DatabaseOther extends Database { return super.insert(theEntity); } - // initialisierungen aus den statischen Tabellen - + protected String getPrimaryKeySequence() { + return "media_id_seq"; + } } diff --git a/source/mircoders/storage/DatabaseRights.java b/source/mircoders/storage/DatabaseRights.java index 0d018d54..6a58601b 100755 --- a/source/mircoders/storage/DatabaseRights.java +++ b/source/mircoders/storage/DatabaseRights.java @@ -32,17 +32,7 @@ package mircoders.storage; import mir.log.LoggerWrapper; import mir.storage.Database; -import mir.storage.StorageObjectFailure; - -/** - * - *

Title:

- *

Description:

- *

Copyright: Copyright (c) 2003

- *

Company:

- * @author not attributable - * @version 1.0 - */ +import mir.storage.DatabaseFailure; public class DatabaseRights extends Database { private static DatabaseRights instance; @@ -54,7 +44,7 @@ public class DatabaseRights extends Database { return instance; } - private DatabaseRights() throws StorageObjectFailure { + private DatabaseRights() throws DatabaseFailure { super(); logger = new LoggerWrapper("Database.Rights"); diff --git a/source/mircoders/storage/DatabaseTopics.java b/source/mircoders/storage/DatabaseTopics.java index a478fef5..bb13cd3b 100755 --- a/source/mircoders/storage/DatabaseTopics.java +++ b/source/mircoders/storage/DatabaseTopics.java @@ -40,17 +40,7 @@ import mir.entity.Entity; import mir.entity.EntityBrowser; import mir.log.LoggerWrapper; import mir.storage.Database; -import mir.storage.StorageObjectFailure; - -/** - * - *

Title:

- *

Description:

- *

Copyright: Copyright (c) 2003

- *

Company:

- * @author not attributable - * @version 1.0 - */ +import mir.storage.DatabaseFailure; public class DatabaseTopics extends Database { private static DatabaseTopics instance; @@ -62,7 +52,7 @@ public class DatabaseTopics extends Database { return instance; } - private DatabaseTopics() throws StorageObjectFailure { + private DatabaseTopics() throws DatabaseFailure { super(); logger = new LoggerWrapper("Database.Topics"); @@ -71,7 +61,7 @@ public class DatabaseTopics extends Database { entityClass = mircoders.entity.EntityTopics.class; } - public List getPopupData() throws StorageObjectFailure { + public List getPopupData() throws DatabaseFailure { List result = new ArrayList(); Iterator i = new EntityBrowser(this, "", "title", 100, -1, 0); diff --git a/source/mircoders/storage/DatabaseUploadedMedia.java b/source/mircoders/storage/DatabaseUploadedMedia.java index 0e173ded..7f9bc711 100755 --- a/source/mircoders/storage/DatabaseUploadedMedia.java +++ b/source/mircoders/storage/DatabaseUploadedMedia.java @@ -36,7 +36,7 @@ import mir.entity.Entity; import mir.entity.EntityBrowser; import mir.log.LoggerWrapper; import mir.storage.Database; -import mir.storage.StorageObjectFailure; +import mir.storage.DatabaseFailure; public class DatabaseUploadedMedia extends Database { private static DatabaseUploadedMedia instance; @@ -55,7 +55,6 @@ public class DatabaseUploadedMedia extends Database { logger = new LoggerWrapper("Database.UploadedMedia"); mainTable="uploaded_media"; - primaryKeySequence="media_id_seq"; entityClass = mircoders.entity.EntityUploadedMedia.class; } @@ -64,7 +63,7 @@ public class DatabaseUploadedMedia extends Database { * returns the media_type that belongs to the media item (via entityrelation) * where db-flag is_published is true */ - public Entity getMediaType(Entity ent) throws StorageObjectFailure { + public Entity getMediaType(Entity ent) throws DatabaseFailure { Entity type=null; try { Iterator i = new EntityBrowser(DatabaseMediaType.getInstance(), ent.getFieldValue("to_media_type") + " = id" , "id", 1); @@ -74,9 +73,12 @@ public class DatabaseUploadedMedia extends Database { catch (Throwable t) { logger.error("DatabaseUploadedMedia :: failed to get media_type: " + t.getMessage()); - throw new StorageObjectFailure("DatabaseUploadedMedia :: failed to get media_type", t); + throw new DatabaseFailure("DatabaseUploadedMedia :: failed to get media_type", t); } return type; } + protected String getPrimaryKeySequence() { + return "media_id_seq"; + } } diff --git a/source/mircoders/storage/DatabaseUsers.java b/source/mircoders/storage/DatabaseUsers.java index 66ffa864..cbe7743c 100755 --- a/source/mircoders/storage/DatabaseUsers.java +++ b/source/mircoders/storage/DatabaseUsers.java @@ -32,25 +32,12 @@ package mircoders.storage; import mir.log.LoggerWrapper; import mir.storage.Database; -import mir.storage.StorageObjectFailure; - -/** - * - *

Title:

- *

Description:

- *

Copyright: Copyright (c) 2003

- *

Company:

- * @author not attributable - * @version 1.0 - */ +import mir.storage.DatabaseFailure; public class DatabaseUsers extends Database { private static DatabaseUsers instance; - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh public synchronized static DatabaseUsers getInstance() { if (instance == null) { instance = new DatabaseUsers(); @@ -58,7 +45,7 @@ public class DatabaseUsers extends Database { return instance; } - private DatabaseUsers() throws StorageObjectFailure { + private DatabaseUsers() throws DatabaseFailure { super(); logger = new LoggerWrapper("Database.Users"); diff --git a/source/mircoders/storage/DatabaseVideo.java b/source/mircoders/storage/DatabaseVideo.java index 7bcdaef5..eaff7e4d 100755 --- a/source/mircoders/storage/DatabaseVideo.java +++ b/source/mircoders/storage/DatabaseVideo.java @@ -36,17 +36,7 @@ import mir.entity.Entity; import mir.log.LoggerWrapper; import mir.misc.StringUtil; import mir.storage.Database; -import mir.storage.StorageObjectFailure; - -/** - * - *

Title:

- *

Description:

- *

Copyright: Copyright (c) 2003

- *

Company:

- * @author not attributable - * @version 1.0 - */ +import mir.storage.DatabaseFailure; public class DatabaseVideo extends Database { @@ -67,11 +57,10 @@ public class DatabaseVideo extends Database { logger = new LoggerWrapper("Database.Video"); mainTable = "video"; - primaryKeySequence = "media_id_seq"; entityClass = mircoders.entity.EntityVideo.class; } - public void update(Entity theEntity) throws StorageObjectFailure { + public void update(Entity theEntity) throws DatabaseFailure { String date = theEntity.getFieldValue("date"); if (date == null) { date = StringUtil.date2webdbDate(new GregorianCalendar()); @@ -81,7 +70,7 @@ public class DatabaseVideo extends Database { super.update(theEntity); } - public String insert(Entity theEntity) throws StorageObjectFailure { + public String insert(Entity theEntity) throws DatabaseFailure { String date = theEntity.getFieldValue("date"); if (date == null) { date = StringUtil.date2webdbDate(new GregorianCalendar()); @@ -90,4 +79,7 @@ public class DatabaseVideo extends Database { return super.insert(theEntity); } + protected String getPrimaryKeySequence() { + return "media_id_seq"; + } } -- 2.11.0