* 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();
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 {
}
/** {@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);
}
* 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 {
/**
* 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);
}
}
*/
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 <code>Entity</code> represents a persistent data object, typically
* stored in a database.<p>
*
- * @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 {
/**
* 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.
/** 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;
}
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;
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;
}
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;
* Container class for lists of Entities.
* Now implements @see mir.database.store.StorableObject.
*
- * @author <RK>
+ * @author rk
* first version 27.6.1999
*
* @version 1.1 (cleaned up)
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());
import java.util.List;
import mir.entity.EntityBrowser;
-import mir.storage.StorageObjectFailure;
-
-/**
- * <p>Title: </p>
- * <p>Description: </p>
- * <p>Copyright: Copyright (c) 2003</p>
- * <p>Company: </p>
- * @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);
return new EntityListAdapter(aModel, aDefinition, browser, aLimit);
}
catch (Throwable t) {
- throw new StorageObjectFailure(t);
+ throw new DatabaseFailure(t);
}
}
}
\ No newline at end of file
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 {
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);
}
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 {
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);
*/
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,
* ) and just override the things that need to be specific. see MediaHandlerAudio
*
* @author <mh@nadir.org>, 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 {
--- /dev/null
+/*
+ * 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 <code>aMaxWidth</code> and <code>aMaxHeight</code>, provided
+ * this requires at least <code>aMinResize</code> 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;
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
--- /dev/null
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two. You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries. If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mir.media.image;\r
+\r
+import com.sun.media.jai.codec.ByteArraySeekableStream;\r
+import com.sun.media.jai.codec.FileSeekableStream;\r
+import com.sun.media.jai.codec.SeekableStream;\r
+import mir.log.LoggerWrapper;\r
+import mir.media.MediaExc;\r
+import mir.media.MediaFailure;\r
+\r
+import javax.media.jai.ImageLayout;\r
+import javax.media.jai.InterpolationBilinear;\r
+import javax.media.jai.JAI;\r
+import javax.media.jai.ParameterBlockJAI;\r
+import java.awt.*;\r
+import java.awt.image.ColorModel;\r
+import java.awt.image.DataBuffer;\r
+import java.awt.image.PixelInterleavedSampleModel;\r
+import java.awt.image.RenderedImage;\r
+import java.io.*;\r
+\r
+public class JAIImageProcessor implements ImageProcessor {\r
+ static final LoggerWrapper logger = new LoggerWrapper("media.image.jai");\r
+\r
+ private RenderedImage image;\r
+ private RenderedImage scaledImage;\r
+\r
+ public JAIImageProcessor(RenderedImage anImage) {\r
+ image = anImage;\r
+ scaledImage = anImage;\r
+ }\r
+\r
+ public JAIImageProcessor(SeekableStream anImageStream) {\r
+ RenderedImage tempImage = JAI.create("stream", anImageStream);\r
+ ParameterBlockJAI params = new ParameterBlockJAI("format");\r
+ int bands[];\r
+ int nrComponents;\r
+\r
+\r
+ params.addSource(tempImage);\r
+ params.setParameter("dataType", DataBuffer.TYPE_BYTE);\r
+\r
+ ImageLayout layout = new ImageLayout();\r
+ nrComponents = tempImage.getColorModel().getNumColorComponents();\r
+\r
+ bands = new int[nrComponents];\r
+ for (int i=0; i<nrComponents; i++)\r
+ bands[i]=i;\r
+\r
+ layout.setColorModel(ColorModel.getRGBdefault());\r
+ layout.setSampleModel(\r
+ new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE,\r
+ tempImage.getWidth(),\r
+ tempImage.getHeight(),\r
+ nrComponents,\r
+ nrComponents*tempImage.getWidth(),\r
+ bands));\r
+\r
+ RenderingHints hints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, layout);\r
+\r
+ image = JAI.create("format", params, hints);\r
+\r
+ scaledImage = image;\r
+ }\r
+\r
+ public JAIImageProcessor(File aFile) throws IOException {\r
+ this(new FileSeekableStream(aFile));\r
+ }\r
+\r
+ public JAIImageProcessor(byte[] anImageData) throws IOException {\r
+ this(new ByteArraySeekableStream(anImageData));\r
+ }\r
+\r
+ public void descaleImage(int aMaxSize) throws MediaExc {\r
+ descaleImage(aMaxSize, 0);\r
+ }\r
+\r
+ public void descaleImage(int aMaxSize, float aMinDescale) throws MediaExc {\r
+ descaleImage(aMaxSize, aMaxSize, aMinDescale, 0);\r
+ }\r
+\r
+ public void descaleImage(int aMaxSize, int aMinResize) throws MediaExc {\r
+ descaleImage(aMaxSize, aMaxSize, 0, aMinResize);\r
+ }\r
+\r
+ public void descaleImage(int aMaxSize, float aMinDescale, int aMinResize) throws MediaExc {\r
+ descaleImage(aMaxSize, aMaxSize, aMinDescale, aMinResize);\r
+ }\r
+\r
+ /**\r
+ * {@inheritDoc}\r
+ */\r
+ public void descaleImage(int aMaxWidth, int aMaxHeight, float aMinDescale, int aMinResize) throws MediaExc {\r
+ float scale;\r
+ scaledImage = image;\r
+\r
+ if ((aMaxWidth>0 && image.getWidth()>aMaxWidth+aMinResize-1) || (aMaxHeight>0 && image.getHeight()>aMaxHeight+aMinResize-1))\r
+ {\r
+ logger.info("Scaling image");\r
+\r
+ scale=1;\r
+\r
+ if (aMaxWidth>0 && image.getWidth()>aMaxWidth) {\r
+ scale = Math.min(scale, (float) aMaxWidth / (float) image.getWidth());\r
+ }\r
+ if (aMaxHeight>0 && image.getHeight()>aMaxHeight) {\r
+ scale = Math.min(scale, (float) aMaxHeight / (float) image.getHeight());\r
+ }\r
+\r
+ if (1-scale>aMinDescale) {\r
+ scaleImage(scale);\r
+ }\r
+ }\r
+ }\r
+\r
+ public void scaleImage(float aScalingFactor) throws MediaExc {\r
+ ParameterBlockJAI params = new ParameterBlockJAI("scale");\r
+ params.addSource(image);\r
+\r
+ params.setParameter("xScale", aScalingFactor);\r
+ params.setParameter("yScale", aScalingFactor);\r
+ params.setParameter("xTrans", 0.0F);\r
+ params.setParameter("yTrans", 0.0F);\r
+ params.setParameter("interpolation", new InterpolationBilinear());\r
+ scaledImage = JAI.create("scale", params);\r
+ }\r
+\r
+ public int getWidth() {\r
+ return image.getWidth();\r
+ }\r
+\r
+ public int getHeight() {\r
+ return image.getHeight();\r
+ }\r
+\r
+ public int getScaledWidth() {\r
+ return scaledImage.getWidth();\r
+ }\r
+\r
+ public int getScaledHeight() {\r
+ return scaledImage.getHeight();\r
+ }\r
+\r
+ public void writeScaledData(OutputStream aStream, String anImageType) {\r
+ JAI.create("encode", scaledImage, aStream, anImageType, null);\r
+ }\r
+\r
+ public byte[] getScaledData(String anImageType) {\r
+ ByteArrayOutputStream outputStream = new ByteArrayOutputStream();\r
+ writeScaledData(outputStream, anImageType);\r
+ return outputStream.toByteArray();\r
+ }\r
+\r
+ public void writeScaledData(File aFile, String anImageType) throws MediaExc {\r
+ try {\r
+ writeScaledData(new BufferedOutputStream(new FileOutputStream(aFile),8192), anImageType);\r
+ }\r
+ catch (FileNotFoundException f) {\r
+ throw new MediaFailure(f);\r
+ }\r
+ }\r
+}\r
+\r
+\r
+\r
+\r
+\r
+\r
+\r
+\r
+\r
+\r
+\r
+\r
+\r
+\r
+\r
+\r
+\r
+\r
+\r
+\r
*/
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.
}
}
- /**
- * * 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();
}
}
- /**
- * 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"));
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);
- }
- }
-
}
* 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 {
}
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");
* 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
*/
* 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();
}
}
}
- 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());
if ((configuration.getString("RootUri") == null) || configuration.getString("RootUri").equals("")) {
configuration.setProperty("RootUri", request.getContextPath());
}
+
setEncoding(request);
process(request, response);
}
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";
}
* 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 {
* @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();
/*
- * Copyright (C) 2001, 2002 The Mir-coders group
+ * Copyright (C) 2001-2005 The Mir-coders group
*
* This file is part of Mir.
*
*/
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;
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 <code>Database.Logfile</code>,
- * <code>Database.Username</code>,<code>Database.Password</code>,
- * <code>Database.Host</code> und <code>Database.Adaptor</code>
- * 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");
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);
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 <code>Database</code>
*/
- public List getFieldNames() throws StorageObjectFailure {
+ public List getFieldNames() throws DatabaseFailure {
if (fieldNames == null) {
acquireMetaData();
}
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;
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();
}
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;
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;
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;
// 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();
default:
outValue = "<unsupported value>";
- 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);
}
}
}
/**
- * 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);
}
}
- 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
}
}
- // 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<aLimit)) && resultSet.next()) {
- theResultEntity = makeEntityFromResultSet(resultSet);
- theReturnList.add(theResultEntity);
+ entity = makeEntityFromResultSet(resultSet);
+ result.add(entity);
position++;
}
+
hasMore = resultSet.next();
resultSet.close();
}
- if (theReturnList != null) {
- // now we decide if we have to know an overall count...
- theReturnList.setOffset(anOffset);
- theReturnList.setWhere(aWhereClause);
- theReturnList.setOrder(anOrderByClause);
- theReturnList.setStorage(this);
- theReturnList.setLimit(aLimit);
+ if (result != null) {
+ result.setOffset(anOffset);
+ result.setWhere(aWhereClause);
+ result.setOrder(anOrderByClause);
+ result.setStorage(this);
+ result.setLimit(aLimit);
if (hasMore) {
- theReturnList.setNextBatch(anOffset + aLimit);
+ result.setNextBatch(anOffset + aLimit);
}
if (anExtraTables==null && StoreUtil.extendsStorableEntity(entityClass)) {
- StoreIdentifier sid = theReturnList.getStoreIdentifier();
+ StoreIdentifier sid = result.getStoreIdentifier();
logger.debug("CACHE (add): " + sid.toString());
o_store.add(sid);
}
}
}
- catch (SQLException sqe) {
- throwSQLException(sqe, "selectByWhereClause");
+ catch (Throwable e) {
+ throw new DatabaseFailure(e);
}
finally {
try {
if (connection != null) {
- freeConnection(connection, statement);
+ freeConnection(connection);
}
} catch (Throwable t) {
}
}
- return theReturnList;
+ return result;
}
- private Entity makeEntityFromResultSet(ResultSet rs)
- throws StorageObjectFailure {
- Map theResultHash = new HashMap();
+ private Entity makeEntityFromResultSet(ResultSet rs) {
+ Map fields = new HashMap();
String theResult = null;
int type;
Entity returnEntity = null;
}
for (int i = 0; i < getFieldNames().size(); i++) {
- // alle durchlaufen bis nix mehr da
type = fieldTypes[i];
if (type == java.sql.Types.LONGVARBINARY) {
}
if (theResult != null) {
- theResultHash.put(getFieldNames().get(i), theResult);
+ fields.put(getFieldNames().get(i), theResult);
}
}
if (entityClass != null) {
returnEntity = createNewEntity();
- returnEntity.setFieldValues(theResultHash);
+ returnEntity.setFieldValues(fields);
if (returnEntity instanceof StorableObject) {
logger.debug("CACHE: ( in) " + returnEntity.getId() + " :" + mainTable);
o_store.add(((StorableObject) returnEntity).getStoreIdentifier());
}
- } else {
- throwStorageObjectException("Internal Error: entityClass not set!");
+ }
+ else {
+ throw new DatabaseExc("Internal Error: entityClass not set!");
}
}
- catch (IOException e) {
- throwStorageObjectException("IOException! -- " + e.getMessage());
- }
- catch (SQLException sqe) {
- throwSQLException(sqe, "makeEntityFromResultSet");
-
- return null;
+ catch (Throwable e) {
+ throw new DatabaseFailure(e);
}
return returnEntity;
* Inserts an entity into the database.
*
* @param anEntity
- * @return der Wert des Primary-keys der eingef?gten Entity
+ * @return the value of the primary key of the inserted record
*/
- public String insert(Entity anEntity) throws StorageObjectFailure {
+ public String insert(Entity anEntity) throws DatabaseFailure {
invalidateStore();
+ RecordInserter inserter =
+ new RecordInserter(mainTable, getPrimaryKeySequence());
+
String returnId = null;
Connection con = null;
PreparedStatement pstmt = null;
try {
- StringBuffer f = new StringBuffer();
- StringBuffer v = new StringBuffer();
- String aField;
- String aValue;
- boolean firstField = true;
+ String fieldName;
// make sql-string
for (int i = 0; i < getFieldNames().size(); i++) {
- aField = (String) getFieldNames().get(i);
-
- if (!aField.equals(primaryKeyField)) {
- aValue = null;
+ fieldName = (String) getFieldNames().get(i);
+ if (!fieldName.equals(primaryKeyField)) {
// exceptions
- if (!anEntity.hasFieldValue(aField) && (
- aField.equals("webdb_create") ||
- aField.equals("webdb_lastchange"))) {
- aValue = "NOW()";
+ if (!anEntity.hasFieldValue(fieldName) && (
+ fieldName.equals("webdb_create") ||
+ fieldName.equals("webdb_lastchange"))) {
+ inserter.assignVerbatim(fieldName, "now()");
}
else {
- if (anEntity.hasFieldValue(aField)) {
- aValue =
- "'" +
- JDBCStringRoutines.escapeStringLiteral(anEntity.getFieldValue(aField)) + "'";
- }
- }
-
- // wenn Wert gegeben, dann einbauen
- if (aValue != null) {
- if (firstField == false) {
- f.append(",");
- v.append(",");
+ if (anEntity.hasFieldValue(fieldName)) {
+ inserter.assignString(fieldName, anEntity.getFieldValue(fieldName));
}
- else {
- firstField = false;
- }
-
- f.append(aField);
- v.append(aValue);
}
}
}
- // end for
-
- // insert into db
- StringBuffer sqlBuf =
- new StringBuffer("insert into ").append(mainTable).append("(").append(f)
- .append(") values (").append(v).append(")");
- String sql = sqlBuf.toString();
- logQueryBefore(sql);
con = obtainConnection();
- con.setAutoCommit(false);
- pstmt = con.prepareStatement(sql);
-
- int ret = pstmt.executeUpdate();
-
- if (ret == 0) {
- //insert failed
- return null;
- }
+ returnId = inserter.execute(con);
-// pstmt = con.prepareStatement("select currval('" + + "_id_seq')");
-
- returnId = getLatestInsertedId(con);
anEntity.setId(returnId);
}
- catch (SQLException sqe) {
- throwSQLException(sqe, "insert");
- }
finally {
try {
- con.setAutoCommit(true);
+ freeConnection(con, pstmt);
}
catch (Exception e) {
}
*
* @param theEntity
*/
- public void update(Entity theEntity) throws StorageObjectFailure {
- Connection con = null;
- PreparedStatement pstmt = null;
-
- /** todo this is stupid: why do we prepare statement, when we
- * throw it away afterwards. should be regular statement
- * update/insert could better be one routine called save()
- * that chooses to either insert or update depending if we
- * have a primary key in the entity. i don't know if we
- * still need the streamed input fields. // rk */
-
- /** todo extension: check if Entity did change, otherwise we don't need
- * the roundtrip to the database */
- /** invalidating corresponding entitylists in o_store*/
+ public void update(Entity theEntity) throws DatabaseFailure {
+ Connection connection = null;
invalidateStore();
- String id = theEntity.getId();
- String aField;
- StringBuffer fv = new StringBuffer();
- boolean firstField = true;
+ RecordUpdater generator = new RecordUpdater(getTableName(), theEntity.getId());
+
+ String field;
// build sql statement
for (int i = 0; i < getFieldNames().size(); i++) {
- aField = (String) getFieldNames().get(i);
-
- // only normal cases
- // todo if entity.hasFieldValue returns false, then the value should be stored as null
- if (!(aField.equals(primaryKeyField) ||
- aField.equals("webdb_create") ||
- aField.equals("webdb_lastchange"))) {
- if (theEntity.hasFieldValue(aField)) {
- if (firstField == false) {
- fv.append(", ");
- }
- else {
- firstField = false;
- }
+ field = (String) getFieldNames().get(i);
- fv.append(aField).append("='").append(JDBCStringRoutines.escapeStringLiteral(theEntity.getFieldValue(aField))).append("'");
+ if (!(field.equals(primaryKeyField) ||
+ field.equals("webdb_create") ||
+ field.equals("webdb_lastchange") ||
+ binaryFields.contains(field))) {
- // fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getFieldValue(aField))).append("'");
+ if (theEntity.hasFieldValue(field)) {
+ generator.assignString(field, theEntity.getFieldValue(field));
}
}
}
- StringBuffer sql =
- new StringBuffer("update ").append(mainTable).append(" set ").append(fv);
-
// exceptions
- if (getFieldNames().contains("webdb_lastchange")) {
- sql.append(",webdb_lastchange=NOW()");
+ if (hasField("webdb_lastchange")) {
+ generator.assignVerbatim("webdb_lastchange", "now()");
}
// special case: the webdb_create requires the field in yyyy-mm-dd HH:mm
// format so anything extra will be ignored. -mh
- if (getFieldNames().contains("webdb_create") &&
+ if (hasField("webdb_create") &&
theEntity.hasFieldValue("webdb_create")) {
// minimum of 10 (yyyy-mm-dd)...
if (theEntity.getFieldValue("webdb_create").length() >= 10) {
// 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;
stmt = con.createStatement();
res = stmt.executeUpdate(sql);
}
- catch (SQLException sqe) {
- throwSQLException(sqe, "delete");
+ catch (Throwable e) {
+ throw new DatabaseFailure(e);
}
finally {
freeConnection(con, stmt);
return false;
}
- /**
- * Diese Methode fuehrt den Sqlstring <i>sql</i> 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();
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();
return result;
}
catch (Throwable e) {
- throw new StorageObjectFailure(e);
+ throw new DatabaseFailure(e);
}
}
* Executes 1 sql statement and returns the results as a <code>List</code> of
* <code>Map</code>s
*/
- 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 {
return result;
}
catch (Throwable e) {
- throw new StorageObjectFailure(e);
+ throw new DatabaseFailure(e);
}
finally {
if (connection!=null) {
* Executes 1 sql statement and returns the first result row as a <code>Map</code>s
* (<code>null</code> 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 {
}
}
catch (Throwable t) {
- throw new StorageObjectFailure(t);
+ throw new DatabaseFailure(t);
}
}
* Executes 1 sql statement and returns the first column of the first result row as a <code>String</code>s
* (<code>null</code> 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)
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) {
}
public int executeUpdate(Statement stmt, String sql)
- throws StorageObjectFailure, SQLException {
+ throws DatabaseFailure, SQLException {
int rs;
logQueryBefore(sql);
}
public int executeUpdate(String sql)
- throws StorageObjectFailure, SQLException {
+ throws DatabaseFailure, SQLException {
int result = -1;
Connection con = null;
PreparedStatement pstmt = null;
}
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);
/**
* 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();
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";
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);
}
}
}
- /**
- * 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
/**
* 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();
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();
}
}
+ /**
+ * 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));
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();
- }
- }
}
--- /dev/null
+/*
+ * 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.storage;
+
+import multex.Exc;
+
+public class DatabaseExc extends Exc {
+ public DatabaseExc(String aMessage) {
+ super(aMessage);
+ }
+}
--- /dev/null
+/*
+ * 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.storage;
+
+import multex.Failure;
+
+
+/**
+ * Exception for all occuring failures in the database-layer
+ * @author idefix
+ */
+public class DatabaseFailure extends Failure {
+ /**
+ * Constructor StorageObjectException.
+ * @param e
+ */
+ public DatabaseFailure(Throwable e) {
+ super("", e);
+ }
+
+ /**
+ * Standard constructor
+ */
+ public DatabaseFailure() {
+ super("A failure occured", null);
+ }
+
+ /**
+ * Construktor with message
+ * @param String msg
+ */
+ public DatabaseFailure(String msg, Throwable e) {
+ super(msg, e);
+ }
+}
--- /dev/null
+/*\r
+ * Copyright (C) 2005 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two. You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries. If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mir.storage;\r
+\r
+import java.sql.Connection;\r
+import java.sql.PreparedStatement;\r
+import java.sql.ResultSet;\r
+import java.sql.SQLException;\r
+import java.util.Date;\r
+\r
+/**\r
+ * Class to generate insert statements\r
+ */\r
+public class RecordInserter extends StatementGenerator {\r
+\r
+ public RecordInserter(String aTableName, String aSequenceName) {\r
+ tableName = aTableName;\r
+ sequenceName = aSequenceName;\r
+ }\r
+\r
+ /**\r
+ * Assigns a value to a string typed field\r
+ */\r
+ public void assignString(String aFieldName, String aValue) {\r
+ assignObject(aFieldName, aValue);\r
+ }\r
+\r
+ /**\r
+ * Assigns a value to a date/time typed field\r
+ */\r
+ public void assignDate(String aFieldName, Date aDate) {\r
+ assignObject(aFieldName, new java.sql.Date(aDate.getTime()));\r
+ }\r
+\r
+ public void assignVerbatim(String aFieldName, String aText) {\r
+ if (firstAssignment) {\r
+ appendQuery("insert into " + tableName + "(");\r
+ firstAssignment = false;\r
+ }\r
+ else {\r
+ appendQuery(",");\r
+ values.append(",");\r
+ }\r
+\r
+ values.append(aText);\r
+\r
+ appendQuery(aFieldName);\r
+ }\r
+\r
+ /**\r
+ * Executes the statement. Returns the id of the insterted record.\r
+ */\r
+ public String execute(Connection aConnection) throws DatabaseFailure {\r
+ appendQuery(")");\r
+ appendQuery(CRLF);\r
+ appendQuery("values (");\r
+ appendQuery(values.toString());\r
+ appendQuery(")");\r
+\r
+ try {\r
+ int modified = executeWithModifiedCount(aConnection);\r
+ if (modified!=1) {\r
+ throw new Exception("modified count != 1 after insert");\r
+ }\r
+\r
+ PreparedStatement statement = aConnection.prepareStatement("select currval('" + sequenceName + "')");\r
+ ResultSet rs = statement.executeQuery();\r
+ rs.next();\r
+ return rs.getString(1);\r
+ }\r
+ catch (Throwable e) {\r
+ throw new DatabaseFailure(e);\r
+ }\r
+ }\r
+\r
+ private void assignObject(String aFieldName, Object anObject) {\r
+ appendParameter(anObject);\r
+\r
+ assignVerbatim(aFieldName, "?");\r
+ }\r
+\r
+ private String tableName;\r
+ private static final String CRLF = "\n\r";\r
+ private boolean firstAssignment = true;\r
+ private String sequenceName;\r
+ private StringBuffer values = new StringBuffer();\r
+}
\ No newline at end of file
--- /dev/null
+/*\r
+ * Copyright (C) 2005 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two. You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries. If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mir.storage;\r
+\r
+import java.sql.Connection;\r
+import java.sql.ResultSet;\r
+import java.util.*;\r
+\r
+/**\r
+ * Class to generate update statements\r
+ */\r
+public class RecordRetriever extends StatementGenerator {\r
+ public RecordRetriever(String aTableName, String aPrefix) {\r
+ tableName = aTableName;\r
+ prefix = aPrefix;\r
+ if (prefix == null || "".equals(prefix)) {\r
+ prefix = null;\r
+ }\r
+ extraTables = new ArrayList();\r
+ whereClause = new StringBuffer();\r
+ orderByClause = new StringBuffer();\r
+\r
+ appendQuery("SELECT ");\r
+ }\r
+\r
+ public void addExtraTable(String aTableSpecification) {\r
+ extraTables.add(aTableSpecification);\r
+ }\r
+\r
+ public void addField(String aField) {\r
+ if (firstField) {\r
+ firstField = false;\r
+ }\r
+ else {\r
+ appendQuery(", ");\r
+ }\r
+ if (prefix!=null) {\r
+ appendQuery(prefix);\r
+ appendQuery(".");\r
+ }\r
+\r
+ appendQuery(aField);\r
+ }\r
+\r
+ public void appendStringParameter(String aValue) {\r
+ appendParameter(aValue);\r
+ }\r
+\r
+ public void appendWhereClause(String aPart) {\r
+ whereClause.append(aPart);\r
+ }\r
+\r
+ public void appendOrderByClause(String aPart) {\r
+ orderByClause.append(aPart);\r
+ }\r
+\r
+ public void setLimit(int aLimit) {\r
+ limit = aLimit;\r
+ }\r
+\r
+ public void setOffset(int anOffset) {\r
+ offset = anOffset;\r
+ }\r
+\r
+ /**\r
+ * Executes the statement. Returns then number of records\r
+ * changed\r
+ */\r
+ public ResultSet execute(Connection aConnection) throws DatabaseFailure {\r
+ appendQuery(CRLF);\r
+ appendQuery("FROM ");\r
+ appendQuery(tableName);\r
+ if (prefix!=null) {\r
+ appendQuery(" ");\r
+ appendQuery(prefix);\r
+ }\r
+\r
+ Iterator i = extraTables.iterator();\r
+ while (i.hasNext()) {\r
+ appendQuery(", ");\r
+ appendQuery((String) i.next());\r
+ }\r
+\r
+ if (whereClause.toString().trim().length()>0) {\r
+ appendQuery(CRLF);\r
+ appendQuery("WHERE ");\r
+ appendQuery(whereClause.toString());\r
+ }\r
+\r
+ if (orderByClause.toString().trim().length()>0) {\r
+ appendQuery(CRLF);\r
+ appendQuery("ORDER BY ");\r
+ appendQuery(orderByClause.toString());\r
+ }\r
+\r
+ if (limit > -1) {\r
+ appendQuery(CRLF);\r
+ appendQuery("LIMIT ");\r
+ appendQuery(Integer.toString(limit));\r
+ }\r
+\r
+ if (offset > -1) {\r
+ appendQuery(CRLF);\r
+ appendQuery("OFFSET ");\r
+ appendQuery(Integer.toString(offset));\r
+ }\r
+\r
+ return executeWithResultSet(aConnection);\r
+ }\r
+\r
+ private String tableName;\r
+ private String prefix;\r
+ private List extraTables;\r
+ private boolean firstField = true;\r
+ private StringBuffer whereClause;\r
+ private StringBuffer orderByClause;\r
+ private int limit = -1;\r
+ private int offset = -1;\r
+\r
+ private static final String CRLF = "\n\r";\r
+}
\ No newline at end of file
--- /dev/null
+/*\r
+ * Copyright (C) 2005 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two. You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries. If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mir.storage;\r
+\r
+import java.sql.Connection;\r
+import java.util.Date;\r
+\r
+/**\r
+ * Class to generate update statements\r
+ */\r
+public class RecordUpdater extends StatementGenerator{\r
+ public RecordUpdater(String aTableName, String aRecordId) {\r
+ tableName = aTableName;\r
+ recordId = aRecordId;\r
+ }\r
+\r
+ /**\r
+ * Assigns a value to a string typed field\r
+ */\r
+ public void assignString(String aFieldName, String aValue) {\r
+ assignObject(aFieldName, aValue);\r
+ }\r
+\r
+ /**\r
+ * Assigns a value to a date/time typed field\r
+ */\r
+ public void assignDate(String aFieldName, Date aDate) {\r
+ assignObject(aFieldName, new java.sql.Date(aDate.getTime()));\r
+ }\r
+\r
+ /**\r
+ * Assigns a verbatim value to a field. Use with case: no quoting/escaping\r
+ * will be performed\r
+ **/\r
+ public void assignVerbatim(String aFieldName, String aValue) {\r
+ if (firstAssignment) {\r
+ appendQuery("update " + tableName + " set ");\r
+ firstAssignment = false;\r
+ }\r
+ else {\r
+ appendQuery(",");\r
+ }\r
+\r
+ appendQuery(CRLF);\r
+ appendQuery(" " + aFieldName + " = " + aValue);\r
+ }\r
+\r
+ /**\r
+ * Executes the statement. Returns then number of records\r
+ * changed\r
+ */\r
+ public int execute(Connection aConnection) throws DatabaseFailure {\r
+ appendQuery(CRLF);\r
+ appendQuery("where id = ?");\r
+ appendParameter(recordId);\r
+\r
+ return executeWithModifiedCount(aConnection);\r
+ }\r
+\r
+ private void assignObject(String aFieldName, Object anObject) {\r
+ appendParameter(anObject);\r
+ assignVerbatim(aFieldName, "?");\r
+ }\r
+\r
+ private String tableName;\r
+ private static final String CRLF = "\n\r";\r
+ private String recordId;\r
+ private boolean firstAssignment = true;\r
+}
\ No newline at end of file
--- /dev/null
+/*\r
+ * Copyright (C) 2005 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two. You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries. If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mir.storage;\r
+\r
+import mir.log.LoggerWrapper;\r
+\r
+import java.sql.Connection;\r
+import java.sql.PreparedStatement;\r
+import java.sql.ResultSet;\r
+import java.util.ArrayList;\r
+import java.util.Iterator;\r
+import java.util.List;\r
+\r
+/**\r
+ * Base class for (sql) statement generators\r
+ */\r
+public class StatementGenerator {\r
+ private static LoggerWrapper logger = new LoggerWrapper("Database.Statements");\r
+\r
+ public StatementGenerator() {\r
+ query = new StringBuffer();\r
+ parameters = new ArrayList();\r
+ }\r
+\r
+ protected void appendQuery(String aPart) {\r
+ query.append(aPart);\r
+ }\r
+\r
+ protected void appendParameter(Object aParameter) {\r
+ parameters.add(aParameter);\r
+ }\r
+\r
+ /**\r
+ * Executes the statement. Returns the number of modified records.\r
+ */\r
+ protected int executeWithModifiedCount(Connection aConnection) throws DatabaseFailure {\r
+ long start = System.currentTimeMillis();\r
+\r
+ try {\r
+ aConnection.setAutoCommit(false);\r
+ logQueryBefore(query.toString());\r
+\r
+ PreparedStatement statement = aConnection.prepareStatement(query.toString());\r
+\r
+ int index = 1;\r
+ Iterator i = parameters.iterator();\r
+\r
+ while (i.hasNext()) {\r
+ statement.setObject(index, i.next());\r
+ index++;\r
+ }\r
+\r
+ int result = statement.executeUpdate();\r
+\r
+ logQueryAfter(query.toString(), System.currentTimeMillis() - start);\r
+\r
+ return result;\r
+ }\r
+ catch (Throwable e) {\r
+ logQueryError(query.toString(), System.currentTimeMillis() - start, e);\r
+ System.out.println(e.toString());\r
+\r
+ throw new DatabaseFailure(e);\r
+ }\r
+ finally {\r
+ try {\r
+ aConnection.setAutoCommit(true);\r
+ }\r
+ catch (Exception e) {\r
+ }\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Executes the statement. Returns a resultset.\r
+ */\r
+ protected ResultSet executeWithResultSet(Connection aConnection) throws DatabaseFailure {\r
+ long start = System.currentTimeMillis();\r
+\r
+ try {\r
+ logQueryBefore(query.toString());\r
+\r
+ PreparedStatement statement = aConnection.prepareStatement(query.toString());\r
+\r
+ int index = 1;\r
+ Iterator i = parameters.iterator();\r
+\r
+ while (i.hasNext()) {\r
+ statement.setObject(index, i.next());\r
+ index++;\r
+ }\r
+\r
+ ResultSet result = statement.executeQuery();\r
+\r
+ logQueryAfter(query.toString(), System.currentTimeMillis() - start);\r
+\r
+ return result;\r
+ }\r
+ catch (Throwable e) {\r
+ logQueryError(query.toString(), System.currentTimeMillis() - start, e);\r
+ System.out.println(e.toString());\r
+\r
+ throw new DatabaseFailure(e);\r
+ }\r
+ }\r
+\r
+ private void logQueryBefore(String aQuery) {\r
+ logger.debug("about to perform QUERY " + aQuery);\r
+ }\r
+\r
+ private void logQueryAfter(String aQuery, long aTime) {\r
+ logger.info("QUERY " + aQuery + " took " + aTime + "ms.");\r
+ }\r
+\r
+ private void logQueryError(String aQuery, long aTime, Throwable anException) {\r
+ logger.error("QUERY " + aQuery + " took " + aTime + "ms, but threw exception " + anException.toString());\r
+ }\r
+\r
+\r
+ private StringBuffer query;\r
+ private List parameters;\r
+}\r
+++ /dev/null
-/*
- * 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.storage;
-
-import multex.Exc;
-
-
-/**
- * @author idefix
- */
-public class StorageObjectExc extends Exc {
- public StorageObjectExc() {
- super("Something gone wrong");
- }
-
- public StorageObjectExc(String msg) {
- super(msg);
- }
-}
+++ /dev/null
-/*
- * 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.storage;
-
-import multex.Failure;
-
-
-/**
- * Exception for all occuring failures in the database-layer
- * @author idefix
- */
-public class StorageObjectFailure extends Failure {
- /**
- * Constructor StorageObjectException.
- * @param e
- */
- public StorageObjectFailure(Throwable e) {
- super("", e);
- }
-
- /**
- * Standard constructor
- */
- public StorageObjectFailure() {
- super("A failure occured", null);
- }
-
- /**
- * Constructor with message
- * @param msg
- */
- public StorageObjectFailure(String msg, Throwable e) {
- super(msg, e);
- }
-}
while (!reader.isAtEnd()) {
char c = reader.peek();
+ // TODO: << should result in the first < to be regarded as CDATA
if (c != '<')
readCData();
else {
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;
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;
public String createFilter(String aType, String anExpression,
String aComments, String aTag, String anArticleAction,
- String aCommentAction) throws StorageObjectExc {
+ String aCommentAction) throws DatabaseExc {
FilterInstance instance;
try {
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");
String aComments,
String aTag,
String anArticleAction,
- String aCommentAction) throws StorageObjectExc {
+ String aCommentAction) throws DatabaseExc {
return getFilterGroupForId(aGroupId).createFilter(aType, anExpression,
aComments, aTag, anArticleAction, aCommentAction);
}
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 $
*/
/**
* 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);
}
/**
- *
- * @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);
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
*
*/
/**
* 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;
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);
*
* @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);
* 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);
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
{
/**
* 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();
update();
}
catch (Exception e) {
- throw new StorageObjectFailure(e);
+ throw new DatabaseFailure(e);
}
}
}
*
* 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);
}
}
}
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 {
logger = new LoggerWrapper("Entity.UploadedMedia");
}
- public void update() throws StorageObjectFailure {
+ public void update() throws DatabaseFailure {
super.update();
try {
);
}
catch (SQLException e) {
- throw new StorageObjectFailure(e);
+ throw new DatabaseFailure(e);
}
}
*
* @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;
}
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;
protected MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance();
public MirBasicAdminInterfaceLocalizer() throws MirLocalizerFailure {
-
simpleCommentOperations = new ArrayList();
simpleArticleOperations = new ArrayList();
simpleCommentOperationsMap = new HashMap();
/** {@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()));
}
}
- 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 ;
}
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 {
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 {
return true;
}
- protected void performModification(EntityAdapter aUser, EntityComment aComment) throws StorageObjectFailure {
+ protected void performModification(EntityAdapter aUser, EntityComment aComment) throws DatabaseFailure {
aComment.setFieldValue(field, value);
}
}
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()) {
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);
}
}
return true;
}
- protected void performModification(EntityAdapter aUser, EntityContent anArticle) throws StorageObjectFailure {
+ protected void performModification(EntityAdapter aUser, EntityContent anArticle) throws DatabaseFailure {
anArticle.setFieldValue(field, value);
}
}
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);
}
}
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);
}
}
+++ /dev/null
-/*
- * 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;
-
-/**
- *
- * <p>Title: Image processor</p>
- * <p>Description: Temporary image processor class. (Made for the immediate needs of CMI brasil.
- * Will become obsolete when mh's media handler rewrite is finished. </p>
- * @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; i<nrComponents; i++)
- bands[i]=i;
-
- layout.setColorModel(ColorModel.getRGBdefault());
- layout.setSampleModel(
- new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE,
- tempImage.getWidth(),
- tempImage.getHeight(),
- nrComponents,
- nrComponents*tempImage.getWidth(),
- bands));
-
- RenderingHints hints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, layout);
-
- image = JAI.create("format", params, hints);
-
- scaledImage = image;
- }
-
- public ImageProcessor(File aFile) throws IOException {
- this(new FileSeekableStream(aFile));
- }
-
- public ImageProcessor(byte[] anImageData) throws IOException {
- this(new ByteArraySeekableStream(anImageData));
- }
-
- public void descaleImage(int aMaxSize) throws java.io.IOException {
- descaleImage(aMaxSize, 0);
- }
-
- public void descaleImage(int aMaxSize, float aMinDescale) throws java.io.IOException {
- descaleImage(aMaxSize, aMaxSize, aMinDescale, 0);
- }
-
- public void descaleImage(int aMaxSize, int aMinResize) throws java.io.IOException {
- descaleImage(aMaxSize, aMaxSize, 0, aMinResize);
- }
-
- public void descaleImage(int aMaxSize, float aMinDescale, int aMinResize) throws java.io.IOException {
- descaleImage(aMaxSize, aMaxSize, aMinDescale, aMinResize);
- }
-
- /**
- *
- * Resizes an image to fit inside <code>aMaxWidth</code> and <code>aMaxHeight</code>, provided
- * this requires at least <code>aMinResize</code> 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);
- }
-}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
*/
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;
*
* @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 $
*/
}
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 {
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);
}
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() {
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;
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());
}
}
- /**
- *
- * @param theValues
- * @return
- * @throws ModuleExc
- * @throws ModuleFailure
- */
-
public String set(Map theValues) throws ModuleExc, ModuleFailure {
try {
Entity theEntity = database.selectById((String)theValues.get("id"));
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");
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 {
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;
}
}
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;
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);
}
}
- /**
- *
- * @param theValues
- * @return
- * @throws ModuleExc
- * @throws ModuleFailure
- */
public String set (Map theValues) throws ModuleExc, ModuleFailure {
try {
return super.set(digestPassword(theValues));
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;
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");
import mir.entity.Entity;
import mir.entity.EntityBrowser;
-import mir.storage.StorageObjectFailure;
+import mir.storage.DatabaseFailure;
import mircoders.entity.EntityImages;
import mircoders.storage.DatabaseImages;
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");
import javax.servlet.http.HttpServletRequest;
import mir.entity.Entity;
-import mir.storage.StorageObjectFailure;
+import mir.storage.DatabaseFailure;
import org.apache.lucene.document.Document;
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;
}
import mir.entity.Entity;
import mir.entity.EntityList;
-import mir.storage.StorageObjectFailure;
+import mir.storage.DatabaseFailure;
import mircoders.entity.EntityContent;
import mircoders.storage.DatabaseContentToTopics;
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;k<topics.size();k++){
import mir.entity.Entity;
import mir.entity.EntityList;
-import mir.storage.StorageObjectFailure;
+import mir.storage.DatabaseFailure;
import mircoders.entity.EntityContent;
import mircoders.storage.DatabaseContentToTopics;
super(null, "search_topic", "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;k<topics.size();k++){
import mir.entity.Entity;
import mir.entity.EntityBrowser;
-import mir.storage.StorageObjectFailure;
+import mir.storage.DatabaseFailure;
import mircoders.storage.DatabaseVideo;
import org.apache.lucene.document.Document;
super(null, "search_hasVideo", "hasVideo", null, "hasVideo");
}
- 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");
import mir.servlet.ServletModule;
import mir.servlet.ServletModuleExc;
import mir.servlet.ServletModuleFailure;
-import mir.storage.StorageObjectExc;
+import mir.storage.DatabaseExc;
import mir.util.HTTPRequestParser;
import mir.util.URLBuilder;
import mircoders.abuse.FilterEngine;
logAdminUsage(aRequest, id, "filter modified");
}
}
- catch (StorageObjectExc e) {
+ catch (DatabaseExc e) {
throw new ServletModuleFailure(e);
}
MirGlobal.abuse().getFilterEngine().updateFilterGroup(id, name);
}
}
- catch (StorageObjectExc e) {
+ catch (DatabaseExc e) {
throw new ServletModuleFailure(e);
}
import java.io.IOException;
import java.io.Writer;
import java.util.Map;
+import java.util.List;
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;
String defaultStartTemplate = configuration.getString("Mir.StartTemplate");
try {
- Map mergeData = ServletHelper.makeGenerationData(aRequest, aResponse, getLocales(aRequest),
+ Map templateData = ServletHelper.makeGenerationData(aRequest, aResponse, getLocales(aRequest),
"bundles/admin", "etc/bundles/adminlocal");
- mergeData.put("messages",
- new CachingRewindableIterator(
- new EntityIteratorAdapter("", "webdb_create desc", 10,
- MirGlobal.localizer().dataModel().adapterModel(), "internalMessage", 10, 0)));
-
- mergeData.put("fileeditentries", ( (ServletModuleFileEdit) ServletModuleFileEdit.getInstance()).getEntries());
- mergeData.put("administeroperations", ( (ServletModuleLocalizer) ServletModuleLocalizer.getInstance()).getAdministerOperations());
-
- mergeData.put("searchvalue", null);
- mergeData.put("searchfield", null);
- mergeData.put("searchispublished", null);
- mergeData.put("searcharticletype", null);
- mergeData.put("searchorder", null);
- mergeData.put("selectarticleurl", null);
- mergeData.put("recipes", MirGlobal.localizer().producers().getRecipeNames());
+
+ List messages = EntityAdapterEngine.retrieveAdapterList(model, "internalMessage", "", "webdb_create desc", 10, 0);
+
+ templateData.put("messages", messages);
+
+ templateData.put("fileeditentries", ((ServletModuleFileEdit) ServletModuleFileEdit.getInstance()).getEntries());
+ templateData.put("administeroperations", ((ServletModuleLocalizer) ServletModuleLocalizer.getInstance()).getAdministerOperations());
+
+ templateData.put("searchvalue", null);
+ templateData.put("searchfield", null);
+ templateData.put("searchispublished", null);
+ templateData.put("searcharticletype", null);
+ templateData.put("searchorder", null);
+ templateData.put("selectarticleurl", null);
+ templateData.put("recipes", MirGlobal.localizer().producers().getRecipeNames());
String startTemplate = MirGlobal.localizer().adminInterface().getAdminPageGenerator(
- "admin.start", mergeData,
+ "admin.start", templateData,
ServletHelper.getUserAdapter(aRequest), defaultStartTemplate);
- ServletHelper.generateResponse(aResponse.getWriter(), mergeData, startTemplate);
+ ServletHelper.generateResponse(aResponse.getWriter(), templateData, startTemplate);
}
catch (Exception e) {
throw new ServletModuleFailure(e);
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.JDBCStringRoutines;
import mir.util.SQLQueryBuilder;
import mircoders.module.ModuleComment;
import mircoders.storage.DatabaseComment;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.util.*;
+
/*
* ServletModuleComment - controls navigation for Comments
*
HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
URLBuilder urlBuilder = new URLBuilder();
- int count;
try {
Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
- Object commentList =
- new CachingRewindableIterator(
- new EntityIteratorAdapter( aWhereClause, anOrderByClause, nrEntitiesPerListPage,
- MirGlobal.localizer().dataModel().adapterModel(), "comment", nrEntitiesPerListPage, anOffset)
- );
+ List commentList =
+ EntityAdapterEngine.retrieveAdapterList(model, definition, aWhereClause, anOrderByClause, nrEntitiesPerListPage, anOffset);
responseData.put("nexturl", null);
responseData.put("prevurl", null);
- count=mainModule.getSize(aWhereClause);
-
urlBuilder.setValue("module", "Comment");
urlBuilder.setValue("do", "list");
urlBuilder.setValue("where", aWhereClause);
responseData.put("offset" , new Integer(anOffset).toString());
responseData.put("thisurl" , urlBuilder.getQuery());
- if (count>=anOffset+nrEntitiesPerListPage) {
+ if (commentList.size()>=nrEntitiesPerListPage) {
urlBuilder.setValue("offset", anOffset + nrEntitiesPerListPage);
responseData.put("nexturl" , urlBuilder.getQuery());
}
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);
}
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;
* 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;
/**
* Attaches media to an article
- *
*/
public void attach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
String mediaIdParam = aRequest.getParameter("mid");
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 {
try {
Map categoryMap = new HashMap();
List parts = StringRoutines.splitString(topicCategories[i], ":");
+
String key = null;
String listtype = "0";
String listparameter = "5";
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);
}
}
*/
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; }
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)});
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);
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;
* 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 $
*
*/
contentModule = new ModuleContent();
defaultAction = "defaultAction";
}
- catch (StorageObjectFailure e) {
+ catch (DatabaseFailure e) {
logger.error("servletmoduleopenindy could not be initialized: " + e.getMessage());
}
}
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;
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.*;
+
/**
*
* <p>Title: </p>
public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse)
throws ServletModuleExc, ServletModuleUserExc {
+
try {
HTTPParsedRequest parsedRequest = new HTTPParsedRequest(aRequest,
configuration.getString("Mir.DefaultEncoding"),
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();
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);
}
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 {
responseData.put("from", Integer.toString(aFrom));
- responseData.put("count", Integer.toString(aCount));
responseData.put("to", Integer.toString(aTo));
responseData.put("medialist", aList);
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");
urlBuilder.setValue("offset", anOffset);
thisUrl = urlBuilder.getQuery();
- if (count >= anOffset + nrEntitiesPerListPage) {
+ if (list.size() >= nrEntitiesPerListPage) {
urlBuilder.setValue("offset", anOffset + nrEntitiesPerListPage);
nextPageUrl = urlBuilder.getQuery();
}
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) {
getThumbnail(aRequest, aResponse);
}
- /**
- *
- * @param aRequest
- * @param aResponse
- * @throws ServletModuleExc
- */
public void getThumbnail(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
String id = aRequest.getParameter("id");
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 {
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;
import mircoders.module.ModuleUsers;
import mircoders.storage.DatabaseUsers;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.util.*;
+
/**
*
*
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");
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());
}
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);
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");
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 {
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());
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());
return super.insert(theEntity);
}
+ protected String getPrimaryKeySequence() {
+ return "media_id_seq";
+ }
}
import mir.log.LoggerWrapper;
import mir.storage.Database;
-import mir.storage.StorageObjectFailure;
-
-/**
- * <b>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");
import mir.log.LoggerWrapper;
import mir.storage.Database;
-import mir.storage.StorageObjectFailure;
-
-/**
- * <b>This class implements the access to the comment-table for the
- * media table.
- *
- *
- */
+import mir.storage.DatabaseFailure;
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;
stmt.executeUpdate(sql);
}
catch (SQLException sqe) {
- new StorageObjectFailure(sqe);
+ new DatabaseFailure(sqe);
return false;
}
finally {
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();
}
return instance;
}
- private DatabaseCommentStatus() throws StorageObjectFailure {
+ private DatabaseCommentStatus() throws DatabaseFailure {
super();
mainTable = "comment_status";
import mir.entity.EntityList;
import mir.log.LoggerWrapper;
import mir.storage.Database;
-import mir.storage.StorageObjectFailure;
+import mir.storage.DatabaseFailure;
import mircoders.entity.EntityUploadedMedia;
-/**
- * <b>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;
}
public void addMedia(String commentId, String mediaId) throws
- StorageObjectFailure {
+ DatabaseFailure {
if (commentId == null && mediaId == null) {
return;
}
}
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);
}
public void setMedia(String commentId, String mediaId) throws
- StorageObjectFailure {
+ DatabaseFailure {
if (commentId == null && mediaId == null) {
return;
}
}
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);
}
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;
}
catch (Exception e) {
logger.error("-- delete by commentId failed ");
- throw new StorageObjectFailure(
+ throw new DatabaseFailure(
"-- delete by comment id failed -- delete ", e);
}
finally {
}
}
- 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;
}
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);
}
public void delete(String commentId, String mediaId) throws
- StorageObjectFailure {
+ DatabaseFailure {
if (mediaId == null || commentId == null) {
logger.debug("-- delete media failed -- missing parameter");
return;
}
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);
}
public EntityList getComment(EntityUploadedMedia media) throws
- StorageObjectFailure {
+ DatabaseFailure {
EntityList returnList = null;
if (media != null) {
}
catch (Exception e) {
logger.error("-- get comment failed");
- throw new StorageObjectFailure("-- get comment failed -- ", e);
+ throw new DatabaseFailure("-- get comment failed -- ", e);
}
}
return returnList;
* a relation to a media
*/
- public EntityList getComment() throws StorageObjectFailure {
+ public EntityList getComment() throws DatabaseFailure {
EntityList returnList = null;
ArrayList extraTables = new ArrayList();
}
catch (Exception e) {
logger.error("-- get comment failed");
- throw new StorageObjectFailure("-- get comment failed -- ", e);
+ throw new DatabaseFailure("-- get comment failed -- ", e);
}
return returnList;
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;
-/**
- * <b>this class implements the access to the content-table</b>
- *
- *
- */
+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 ) {
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;
* 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;
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);
return super.delete(id);
}
+ protected String getPrimaryKeySequence() {
+ return "media_id_seq";
+ }
}
import mir.entity.EntityList;
import mir.log.LoggerWrapper;
import mir.storage.Database;
-import mir.storage.StorageObjectFailure;
+import mir.storage.DatabaseFailure;
import mircoders.entity.EntityUploadedMedia;
/**
* <b>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 $
*
*/
}
public void addMedia(String contentId, String mediaId) throws
- StorageObjectFailure {
+ DatabaseFailure {
if (contentId == null && mediaId == null) {
return;
}
}
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);
}
public void setMedia(String contentId, String mediaId) throws
- StorageObjectFailure {
+ DatabaseFailure {
if (contentId == null && mediaId == null) {
return;
}
}
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);
}
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;
}
catch (Exception e) {
logger.error("-- delete by contentId failed ");
- throw new StorageObjectFailure(
+ throw new DatabaseFailure(
"-- delete by content id failed -- delete ", e);
}
finally {
}
}
- 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");
}
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);
}
public void delete(String contentId, String mediaId) throws
- StorageObjectFailure {
+ DatabaseFailure {
if (mediaId == null || contentId == null) {
logger.debug("-- delete media failed -- missing parameter");
return;
}
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);
}
public EntityList getContent(EntityUploadedMedia media) throws
- StorageObjectFailure {
+ DatabaseFailure {
EntityList returnList = null;
if (media != null) {
}
catch (Exception e) {
logger.error("-- get content failed");
- throw new StorageObjectFailure("-- get content failed -- ", e);
+ throw new DatabaseFailure("-- get content failed -- ", e);
}
}
return returnList;
* 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;
}
catch (Exception e) {
logger.error("-- get content failed");
- throw new StorageObjectFailure("-- get content failed -- ", e);
+ throw new DatabaseFailure("-- get content failed -- ", e);
}
return returnList;
}
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;
import java.util.Iterator;
import java.util.List;
-import mir.entity.EntityList;
-import mir.log.LoggerWrapper;
-import mir.storage.Database;
-import mir.storage.StorageObjectFailure;
-import mircoders.entity.EntityContent;
-import mircoders.entity.EntityTopics;
-
/**
* <b>This class implements the 1-n-relation between
* content and topic
* 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) {
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();
}
public void deleteByContentId(String contentId)
- throws StorageObjectFailure {
+ throws DatabaseFailure {
if (contentId == null) {
//theLog.printDebugInfo("-- delete topics failed -- no content id");
return;
}
public void deleteByTopicId(String topicId)
- throws StorageObjectFailure {
+ throws DatabaseFailure {
if (topicId == null) {
//theLog.printDebugInfo("-- delete topics failed -- no topic id");
return;
* 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();
package mircoders.storage;
-/**
- *
- */
-
import mir.log.LoggerWrapper;
import mir.storage.Database;
package mircoders.storage;
-/**
- *
- */
-
import mir.log.LoggerWrapper;
import mir.storage.Database;
import mir.log.LoggerWrapper;
import mir.storage.Database;
-/**
- * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle
- *
- *
- */
-
public class DatabaseImageColor extends Database {
private static DatabaseImageColor instance;
import mir.log.LoggerWrapper;
import mir.storage.Database;
-/**
- * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle
- *
- *
- */
-
public class DatabaseImageFormat extends Database {
private static DatabaseImageFormat instance;
import mir.log.LoggerWrapper;
import mir.storage.Database;
-/**
- * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle
- *
- *
- */
-
public class DatabaseImageLayout extends Database {
private static DatabaseImageLayout instance;
import mir.log.LoggerWrapper;
import mir.storage.Database;
-/**
- *
- * <p>Title: </p>
- * <p>Description: </p>
- * <p>Copyright: Copyright (c) 2003</p>
- * <p>Company: </p>
- * @author not attributable
- * @version 1.0
- */
-
public class DatabaseImageType extends Database {
private static DatabaseImageType instance;
import mir.log.LoggerWrapper;
import mir.misc.StringUtil;
import mir.storage.Database;
-import mir.storage.StorageObjectFailure;
-
-/**
- * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle
- *
- *
- */
+import mir.storage.DatabaseFailure;
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());
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) {
return super.insert(theEntity);
}
+
+ protected String getPrimaryKeySequence() {
+ return "media_id_seq";
+ }
}
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 {
// 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);
import mir.log.LoggerWrapper;
import mir.storage.Database;
-import mir.storage.StorageObjectFailure;
-
-/**
- * <b>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;
return instance;
}
- private DatabaseMediaType() throws StorageObjectFailure
+ private DatabaseMediaType() throws DatabaseFailure
{
super();
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;
import mir.log.LoggerWrapper;
import mir.misc.StringUtil;
import mir.storage.Database;
-import mir.storage.StorageObjectFailure;
-
-/**
- *
- * <p>Title: </p>
- * <p>Description: </p>
- * <p>Copyright: Copyright (c) 2003</p>
- * <p>Company: </p>
- * @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();
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());
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());
return super.insert(theEntity);
}
- // initialisierungen aus den statischen Tabellen
-
+ protected String getPrimaryKeySequence() {
+ return "media_id_seq";
+ }
}
import mir.log.LoggerWrapper;
import mir.storage.Database;
-import mir.storage.StorageObjectFailure;
-
-/**
- *
- * <p>Title: </p>
- * <p>Description: </p>
- * <p>Copyright: Copyright (c) 2003</p>
- * <p>Company: </p>
- * @author not attributable
- * @version 1.0
- */
+import mir.storage.DatabaseFailure;
public class DatabaseRights extends Database {
private static DatabaseRights instance;
return instance;
}
- private DatabaseRights() throws StorageObjectFailure {
+ private DatabaseRights() throws DatabaseFailure {
super();
logger = new LoggerWrapper("Database.Rights");
import mir.entity.EntityBrowser;
import mir.log.LoggerWrapper;
import mir.storage.Database;
-import mir.storage.StorageObjectFailure;
-
-/**
- *
- * <p>Title: </p>
- * <p>Description: </p>
- * <p>Copyright: Copyright (c) 2003</p>
- * <p>Company: </p>
- * @author not attributable
- * @version 1.0
- */
+import mir.storage.DatabaseFailure;
public class DatabaseTopics extends Database {
private static DatabaseTopics instance;
return instance;
}
- private DatabaseTopics() throws StorageObjectFailure {
+ private DatabaseTopics() throws DatabaseFailure {
super();
logger = new LoggerWrapper("Database.Topics");
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);
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;
logger = new LoggerWrapper("Database.UploadedMedia");
mainTable="uploaded_media";
- primaryKeySequence="media_id_seq";
entityClass = mircoders.entity.EntityUploadedMedia.class;
}
* 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);
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";
+ }
}
import mir.log.LoggerWrapper;
import mir.storage.Database;
-import mir.storage.StorageObjectFailure;
-
-/**
- *
- * <p>Title: </p>
- * <p>Description: </p>
- * <p>Copyright: Copyright (c) 2003</p>
- * <p>Company: </p>
- * @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();
return instance;
}
- private DatabaseUsers() throws StorageObjectFailure {
+ private DatabaseUsers() throws DatabaseFailure {
super();
logger = new LoggerWrapper("Database.Users");
import mir.log.LoggerWrapper;
import mir.misc.StringUtil;
import mir.storage.Database;
-import mir.storage.StorageObjectFailure;
-
-/**
- *
- * <p>Title: </p>
- * <p>Description: </p>
- * <p>Copyright: Copyright (c) 2003</p>
- * <p>Company: </p>
- * @author not attributable
- * @version 1.0
- */
+import mir.storage.DatabaseFailure;
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());
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());
return super.insert(theEntity);
}
+ protected String getPrimaryKeySequence() {
+ return "media_id_seq";
+ }
}