From: zapata Date: Sun, 21 Aug 2005 17:09:17 +0000 (+0000) Subject: cleanup / abuse system fix / prepping for a release X-Git-Tag: LATEST_MERGED_1_1~107 X-Git-Url: http://erislabs.net/gitweb/?a=commitdiff_plain;h=6b6b6215ebe066b81f1fa6b0c71a532ca7b4fc3f;hp=afcbbd1dee154b4d24a4a77dacc7e07503dd182c;p=mir.git cleanup / abuse system fix / prepping for a release --- diff --git a/build.xml b/build.xml index f2d98cd2..2b7d3be7 100755 --- a/build.xml +++ b/build.xml @@ -154,6 +154,8 @@ + + diff --git a/lib/avalon-framework-4.0.jar b/lib/avalon-framework-4.0.jar deleted file mode 100755 index 69f4b131..00000000 Binary files a/lib/avalon-framework-4.0.jar and /dev/null differ diff --git a/lib/batik.jar b/lib/batik.jar deleted file mode 100755 index 186927b8..00000000 Binary files a/lib/batik.jar and /dev/null differ diff --git a/lib/fop.jar b/lib/fop.jar deleted file mode 100755 index e48404da..00000000 Binary files a/lib/fop.jar and /dev/null differ diff --git a/lib/jdbc-se2.0.jar b/lib/jdbc-se2.0.jar deleted file mode 100755 index 7b6e322b..00000000 Binary files a/lib/jdbc-se2.0.jar and /dev/null differ diff --git a/lib/jimi.jar b/lib/jimi.jar deleted file mode 100755 index bfbb9f3b..00000000 Binary files a/lib/jimi.jar and /dev/null differ diff --git a/lib/logkit-1.0.jar b/lib/logkit-1.0.jar deleted file mode 100755 index 8b1d2c14..00000000 Binary files a/lib/logkit-1.0.jar and /dev/null differ diff --git a/source/Mir.java b/source/Mir.java index f3a0b79d..7fdcd327 100755 --- a/source/Mir.java +++ b/source/Mir.java @@ -33,7 +33,7 @@ import mir.config.MirPropertiesConfiguration; import mir.log.LoggerWrapper; import mir.servlet.*; import mir.util.StringRoutines; -import mir.util.ExceptionFunctions; +import mir.util.ExceptionRoutines; import multex.Failure; import javax.servlet.ServletConfig; @@ -217,7 +217,7 @@ public class Mir extends AbstractServlet { logger.info("EXECTIME (" + moduleName + "): " + sessionConnectTime + " ms"); } catch (Throwable e) { - Throwable cause = ExceptionFunctions.traceCauseException(e); + Throwable cause = ExceptionRoutines.traceCauseException(e); if (cause instanceof ServletModuleUserExc) handleUserError(aRequest, aResponse, (ServletModuleUserExc) cause); @@ -326,7 +326,7 @@ public class Mir extends AbstractServlet { logger.error("Error handling error: " + e.toString()); try { - Throwable rootException = ExceptionFunctions.traceCauseException(anException); + Throwable rootException = ExceptionRoutines.traceCauseException(anException); PrintWriter writer = aResponse.getWriter(); writer.println("FATAL Error"); diff --git a/source/OpenMir.java b/source/OpenMir.java index 928449e9..ebb32135 100755 --- a/source/OpenMir.java +++ b/source/OpenMir.java @@ -39,14 +39,14 @@ import javax.servlet.http.HttpSession; import mir.servlet.AbstractServlet; import mir.servlet.ServletModuleDispatch; import mir.servlet.ServletModuleUserExc; -import mir.util.ExceptionFunctions; +import mir.util.ExceptionRoutines; import mircoders.servlet.ServletModuleOpenIndy; /** * OpenMir.java - main servlet for open posting and comment feature to articles * * @author RK 1999-2001, the mir-coders group - * @version $Id: OpenMir.java,v 1.35.2.5 2005/07/27 11:46:14 grok Exp $ + * @version $Id: OpenMir.java,v 1.35.2.6 2005/08/21 17:09:18 zapata Exp $ * */ @@ -80,7 +80,7 @@ public class OpenMir extends AbstractServlet { catch (Throwable e) { logger.warn("Error in open publishing", e); - Throwable cause = ExceptionFunctions.traceCauseException(e); + Throwable cause = ExceptionRoutines.traceCauseException(e); if (cause instanceof ServletModuleUserExc) handleUserError(aRequest, aResponse, aResponse.getWriter(), (ServletModuleUserExc) cause); diff --git a/source/default.properties b/source/default.properties index 932624b1..208d2e7e 100755 --- a/source/default.properties +++ b/source/default.properties @@ -188,6 +188,11 @@ Producer.ActionServlet=/servlet/Mir # will be linked to. Producer.ImageRoot=/img +# path to ImageMagick executables. Default is "" (nothing), which +# means executables will be searched using the default system PATH +# example:Producer.Image.ImageMagickPath=/usr/local/ImageMagick/bin +# +Producer.Image.ImageMagickPath= # the url of the video-server Producer.Video.Host=http://indy.code-fu.de/video diff --git a/source/mir/bundle/Bundle.java b/source/mir/bundle/Bundle.java index 04923759..0b92ff12 100755 --- a/source/mir/bundle/Bundle.java +++ b/source/mir/bundle/Bundle.java @@ -32,14 +32,15 @@ package mir.bundle; import java.util.List; /** - * A Bundle represents a set key/value pairs stored in a ".properties" - * text file. Bundles are used for internationalization (language - * translations) and for configuration files (config.properties and - * source/default.properties). - * - * The argument list is used for formating the returned value (FIXME: - * how?) + * A Bundle represents a set key/value pairs, for instane stored in a + * ".properties" text file. Bundles are used for internationalization + * (language translations). */ public interface Bundle { + /** + * Returns a bundle value. The argument list is used for formating the + * returned value: braced expressions like {0}, {1} are replaced with + * appropriate parameter + */ public String getValue(String aKey, List anArguments); } diff --git a/source/mir/entity/Entity.java b/source/mir/entity/Entity.java index 498d9722..10dcad38 100755 --- a/source/mir/entity/Entity.java +++ b/source/mir/entity/Entity.java @@ -39,7 +39,7 @@ import mir.storage.DatabaseFailure; * An Entity represents a persistent data object, typically * stored in a database.

* - * @version $Id: Entity.java,v 1.21.2.13 2005/07/28 21:44:01 grok Exp $ + * @version $Id: Entity.java,v 1.21.2.14 2005/08/21 17:09:18 zapata Exp $ */ public interface Entity { @@ -79,11 +79,11 @@ public interface Entity { /** * 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 + * @param aFieldName The field name whose value has to be set + * @param aValue The new value of the field * @exception DatabaseFailure */ - public void setFieldValue(String theProp, String theValue); + public void setFieldValue(String aFieldName, String aValue); /** * Returns the field names of the Entity @@ -92,12 +92,12 @@ public interface Entity { /** * Returns the value of a field by field name. - * @param field The name of the field + * @param aFieldName The name of the field * @return value of the field */ - public String getFieldValue(String field); + public String getFieldValue(String aFieldName); - public boolean hasFieldValue(String field); + public boolean hasFieldValue(String aFieldName); /** Returns whether fieldName is a valid field name of this Entity. */ diff --git a/source/mir/entity/EntityBrowser.java b/source/mir/entity/EntityBrowser.java index 51b07f61..03855fd6 100755 --- a/source/mir/entity/EntityBrowser.java +++ b/source/mir/entity/EntityBrowser.java @@ -93,7 +93,7 @@ public class EntityBrowser implements RewindableIterator { readCurrentBatch(skip); } catch (Throwable t) { - throw new Failure("Error while rewinging", t); + throw new Failure("Error while rewinding", t); } } diff --git a/source/mir/entity/EntityList.java b/source/mir/entity/EntityList.java index aae8f662..74da98ab 100755 --- a/source/mir/entity/EntityList.java +++ b/source/mir/entity/EntityList.java @@ -29,10 +29,6 @@ */ package mir.entity; -import java.util.ArrayList; -import java.util.Set; - -import mir.config.MirPropertiesConfiguration; import mir.log.LoggerWrapper; import mir.storage.Database; import mir.storage.store.StorableObject; @@ -40,6 +36,10 @@ import mir.storage.store.StoreContainerType; import mir.storage.store.StoreIdentifier; import mir.storage.store.StoreUtil; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + /** * * Container class for lists of Entities. @@ -51,9 +51,8 @@ import mir.storage.store.StoreUtil; * @version 1.1 (cleaned up) */ public class EntityList implements StorableObject { - protected static MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance(); protected LoggerWrapper logger; - private ArrayList theEntityArrayList = new ArrayList(); + private List entities = new ArrayList(); private String whereClause, orderClause; private Database storage; private int offset, limit; @@ -63,7 +62,6 @@ public class EntityList implements StorableObject { logger = new LoggerWrapper("Entity.List"); } -/* get/set EntityClass of Objects stored in EntityList */ public void setStorage(Database aStorage) { storage=aStorage; } @@ -86,15 +84,6 @@ public class EntityList implements StorableObject { } /** - * Returns the WHERE clause that returned this EntityList from the database - * - * @return whereClause The WHERE clause - */ - public String getWhere() { - return whereClause; - } - - /** * Sets the sorting criterium of this EntityList * * @param oc @@ -104,15 +93,6 @@ public class EntityList implements StorableObject { } /** - * Returns the sorting criterium. - * - * @return orderClause The sort order - */ - public String getOrder() { - return orderClause; - } - - /** * Sets the offset * * @param i The offset @@ -165,7 +145,7 @@ public class EntityList implements StorableObject { public void add (Entity anEntity) { if (anEntity!=null) - theEntityArrayList.add(anEntity); + entities.add(anEntity); else logger.warn("EntityList: add called with empty Entity"); } @@ -176,7 +156,7 @@ public class EntityList implements StorableObject { */ public int size() { - return theEntityArrayList.size(); + return entities.size(); } @@ -187,8 +167,7 @@ public class EntityList implements StorableObject { */ public Entity elementAt(int i) { - /** todo check if i is in list.size() */ - return (Entity) theEntityArrayList.get(i); + return (Entity) entities.get(i); } diff --git a/source/mir/entity/adapter/EntityAdapter.java b/source/mir/entity/adapter/EntityAdapter.java index 2fff4d20..e0ab7be5 100755 --- a/source/mir/entity/adapter/EntityAdapter.java +++ b/source/mir/entity/adapter/EntityAdapter.java @@ -29,15 +29,11 @@ */ package mir.entity.adapter; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - import mir.entity.Entity; import mir.util.CachingRewindableIterator; +import mir.util.RewindableIterator; + +import java.util.*; /** An EntityAdapter is a wrapper around an Entity meant to add * missing functionality. It provides "calculated fields" @@ -49,7 +45,7 @@ import mir.util.CachingRewindableIterator; * etc. *

This whole framework is meant to be replaced by hibernate

*/ -public class EntityAdapter implements Map { +public class EntityAdapter { private Entity entity; private EntityAdapterDefinition definition; private Map calculatedFieldsCache; @@ -62,25 +58,18 @@ public class EntityAdapter implements Map { model = aModel; } - public boolean containsKey(Object aKey) { - try { - if (aKey instanceof String) - return entity.hasField((String) aKey) - || definition.hasCalculatedField((String) aKey); - } - catch (Throwable t) { - } - - return false; - } - public boolean equals(Object anObject) { return anObject instanceof EntityAdapter && ((EntityAdapter) anObject).entity.equals(entity); } public int hashCode() { - return entity.hashCode(); + if (entity!=null) { + return entity.hashCode(); + } + else { + return 0; + } } public Entity getEntity() { @@ -91,7 +80,7 @@ public class EntityAdapter implements Map { return model; } - public Object get(Object aKey) { + public Object get(String aKey) { Object result; if (calculatedFieldsCache.containsKey(aKey)) { @@ -103,52 +92,30 @@ public class EntityAdapter implements Map { return result; } - else if (aKey instanceof String) { - return entity.getFieldValue((String) aKey); - } else { - return null; + return entity.getFieldValue((String) aKey); } } - public boolean isEmpty() { - return false; - } - - public Set keySet() { - throw new UnsupportedOperationException("EntityAdapter.keySet()"); - } - - public Object put(Object aKey, Object value) { - throw new UnsupportedOperationException("EntityAdapter.put()"); - } - - public void putAll(Map t) { - throw new UnsupportedOperationException("EntityAdapter.putAll()"); - } - - public Object remove(Object aKey) { - throw new UnsupportedOperationException("EntityAdapter.remove()"); - } - - public int size() { - throw new UnsupportedOperationException("EntityAdapter.size()"); - } - - public Collection values() { - throw new UnsupportedOperationException("EntityAdapter.values()"); - } - - public void clear() { - throw new UnsupportedOperationException("EntityAdapter.clear()"); - } - - public boolean containsValue(Object value) { - throw new UnsupportedOperationException("EntityAdapter.containsValue()"); - } + public Iterator getIterator(String aKey) { + Object result = get(aKey); - public Set entrySet() { - throw new UnsupportedOperationException("EntityAdapter.entrySet()"); + if (result instanceof RewindableIterator) { + ((RewindableIterator) result).rewind(); + return (RewindableIterator) result; + } + else if (result instanceof Iterator) { + return (Iterator) result; + } + else if (result instanceof Collection) { + return ((Collection) result).iterator(); + } + else if (result!=null) { + return Collections.singletonList(result).iterator(); + } + else { + return null; + } } public Object getComplexRelation(String aMainTablePrefix, List someExtraTables, @@ -167,7 +134,7 @@ public class EntityAdapter implements Map { } - public Object getRelation(String aWhereClause, String anOrderByClause, String aDefinition) { + public List getRelation(String aWhereClause, String anOrderByClause, String aDefinition) { try { return EntityAdapterEngine.retrieveAdapterList(model, aDefinition, aWhereClause, anOrderByClause, -1, 0); } diff --git a/source/mir/generator/GeneratorHelper.java b/source/mir/generator/GeneratorHelper.java index 292d8816..ebb40cdb 100755 --- a/source/mir/generator/GeneratorHelper.java +++ b/source/mir/generator/GeneratorHelper.java @@ -45,7 +45,7 @@ public class GeneratorHelper { * Method to initialize the basic generation values for templates. Does nothing which assumes a servlet context. */ - public static Map makeBasicGenerationData(Locale[] aLocales, String aBundle, String aDefaultBundle) throws GeneratorExc{ + public static Map makeBasicGenerationData(Locale[] aLocales, String aBundle, String aDefaultBundle) throws GeneratorExc { try { Map result = new HashMap(); MirGlobal.localizer().producerAssistant().initializeGenerationValueSet(result); diff --git a/source/mir/generator/GeneratorLibraryRepository.java b/source/mir/generator/GeneratorLibraryRepository.java index 7ee9630d..605550d2 100755 --- a/source/mir/generator/GeneratorLibraryRepository.java +++ b/source/mir/generator/GeneratorLibraryRepository.java @@ -31,6 +31,7 @@ package mir.generator; import java.util.HashMap; import java.util.Map; +import java.util.Arrays; import mir.log.LoggerWrapper; import mir.util.SimpleParser; @@ -90,12 +91,16 @@ public class GeneratorLibraryRepository { parser.skip(SPACE); if (!parser.isAtEnd()) { - parser.parse(SEMICOLON, "; expected"); + parser.parse(SEMICOLON, "';' expected"); } } } catch (Exception e) { - throw new GeneratorFailure("Failed to construct generator library: " + e.getMessage(), e); + logger.error("Failed to parse generator library expression " + + Arrays.asList(aSpecification).toString(), e); + + throw new GeneratorFailure("Failed to parse generator library expression " + + Arrays.asList(aSpecification).toString(), e); } } diff --git a/source/mir/generator/tal/template/CoreTemplateNodeLibrary.java b/source/mir/generator/tal/template/CoreTemplateNodeLibrary.java index c440561c..13078495 100755 --- a/source/mir/generator/tal/template/CoreTemplateNodeLibrary.java +++ b/source/mir/generator/tal/template/CoreTemplateNodeLibrary.java @@ -30,12 +30,7 @@ package mir.generator.tal.template; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; +import java.util.*; import mir.generator.tal.interfaces.TALExpressionParser; import mir.generator.tal.interfaces.TALLogger; @@ -321,7 +316,7 @@ public class CoreTemplateNodeLibrary implements TemplateNodeLibrary { if (!omitTag) { content = new StringBuffer(); - Map generatedAttributes = new HashMap(fixedAttributes); + Map generatedAttributes = new TreeMap(fixedAttributes); Iterator i = attributeModifiers.entrySet().iterator(); while (i.hasNext()) { diff --git a/source/mir/media/MediaHandler.java b/source/mir/media/MediaHandler.java index a957c45b..7b5b7e81 100755 --- a/source/mir/media/MediaHandler.java +++ b/source/mir/media/MediaHandler.java @@ -32,7 +32,6 @@ package mir.media; import mir.entity.Entity; import mir.session.UploadedFile; -import java.io.File; import java.io.InputStream; /** @@ -80,7 +79,7 @@ import java.io.InputStream; * ) and just override the things that need to be specific. see MediaHandlerAudio * * @author , the Mir-coders group - * @version $Id: MediaHandler.java,v 1.1.2.6 2005/03/26 11:26:24 zapata Exp $ + * @version $Id: MediaHandler.java,v 1.1.2.7 2005/08/21 17:09:19 zapata Exp $ */ public interface MediaHandler { @@ -95,11 +94,6 @@ public interface MediaHandler { public void store(InputStream anInputStream, Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure; /** - * Store the media content from a file. - */ - public void store(File aFile, Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure; - - /** * Perform production related tasks for this media. */ public void produce(Entity aMedia, Entity aMediaType ) throws MediaExc, MediaFailure; @@ -118,7 +112,6 @@ public interface MediaHandler { */ public InputStream getThumbnail(Entity aMedia) throws MediaExc, MediaFailure; - /** * Returns the mime-type of the media's thumbnail */ @@ -130,19 +123,19 @@ public interface MediaHandler { * in the configuration wich is accessible through the MirConfig * class. */ - public String getStoragePath () throws MediaExc, MediaFailure; + public String getBaseStoragePath () throws MediaExc, MediaFailure; /** * Returns the *relative* filesystem path to where the media * icon content should be stored. It is relative to the path - * returned by getStoragePath() + * returned by getBaseStoragePath() * This path is usually defined * in the configuration wich is accessible through the MirConfig * class. */ - public String getIconStoragePath () throws MediaExc, MediaFailure; + public String getBaseIconStoragePath () throws MediaExc, MediaFailure; - /** + /** * Returns the base URL to that the media is accessible from * to the end user. This could be a URL to another host. * This is used in the Metadata stored in the DB and later on @@ -153,7 +146,7 @@ public interface MediaHandler { */ public String getPublishHost () throws MediaExc, MediaFailure; - /** + /** * Returns the file name of the Icon representing the media type. * It is used in the summary view. * It is usually defined @@ -162,7 +155,7 @@ public interface MediaHandler { */ public String getBigIconName (); - /** + /** * Returns the file name of the small Icon representing * the media type. * It is used in the right hand newswire list of the startpage. diff --git a/source/mir/media/image/JAIImageProcessor.java b/source/mir/media/image/JAIImageProcessor.java deleted file mode 100755 index 17ae00d9..00000000 --- a/source/mir/media/image/JAIImageProcessor.java +++ /dev/null @@ -1,213 +0,0 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with any library licensed under the Apache Software License, - * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library - * (or with modified versions of the above that use the same license as the above), - * and distribute linked combinations including the two. You must obey the - * GNU General Public License in all respects for all of the code used other than - * the above mentioned libraries. If you modify this file, you may extend this - * exception to your version of the file, but you are not obligated to do so. - * If you do not wish to do so, delete this exception statement from your version. - */ - -package mir.media.image; - -import com.sun.media.jai.codec.ByteArraySeekableStream; -import com.sun.media.jai.codec.FileSeekableStream; -import com.sun.media.jai.codec.SeekableStream; -import mir.log.LoggerWrapper; -import mir.media.MediaExc; -import mir.media.MediaFailure; - -import javax.media.jai.ImageLayout; -import javax.media.jai.InterpolationBilinear; -import javax.media.jai.JAI; -import javax.media.jai.ParameterBlockJAI; -import java.awt.*; -import java.awt.image.ColorModel; -import java.awt.image.DataBuffer; -import java.awt.image.PixelInterleavedSampleModel; -import java.awt.image.RenderedImage; -import java.io.*; - -public class JAIImageProcessor implements ImageProcessor { - static final LoggerWrapper logger = new LoggerWrapper("media.image.jai"); - - private RenderedImage image; - private RenderedImage scaledImage; - - public JAIImageProcessor(RenderedImage anImage) { - image = anImage; - scaledImage = anImage; - } - - public JAIImageProcessor(SeekableStream anImageStream) { - RenderedImage tempImage = JAI.create("stream", anImageStream); - ParameterBlockJAI params = new ParameterBlockJAI("format"); - int bands[]; - int nrComponents; - - - params.addSource(tempImage); - params.setParameter("dataType", DataBuffer.TYPE_BYTE); - - ImageLayout layout = new ImageLayout(); - nrComponents = tempImage.getColorModel().getNumColorComponents(); - - bands = new int[nrComponents]; - for (int i=0; i0 && image.getWidth()>aMaxWidth+aMinResize-1) || (aMaxHeight>0 && image.getHeight()>aMaxHeight+aMinResize-1)) - { - logger.info("Scaling image"); - - scale=1; - - if (aMaxWidth>0 && image.getWidth()>aMaxWidth) { - scale = Math.min(scale, (float) aMaxWidth / (float) image.getWidth()); - } - if (aMaxHeight>0 && image.getHeight()>aMaxHeight) { - scale = Math.min(scale, (float) aMaxHeight / (float) image.getHeight()); - } - - if (1-scale>aMinDescale) { - scaleImage(scale); - } - } - } - - public void scaleImage(float aScalingFactor) throws MediaExc { - ParameterBlockJAI params = new ParameterBlockJAI("scale"); - params.addSource(image); - - params.setParameter("xScale", aScalingFactor); - params.setParameter("yScale", aScalingFactor); - params.setParameter("xTrans", 0.0F); - params.setParameter("yTrans", 0.0F); - params.setParameter("interpolation", new InterpolationBilinear()); - scaledImage = JAI.create("scale", params); - } - - public int getWidth() { - return image.getWidth(); - } - - public int getHeight() { - return image.getHeight(); - } - - public int getScaledWidth() { - return scaledImage.getWidth(); - } - - public int getScaledHeight() { - return scaledImage.getHeight(); - } - - public void writeScaledData(OutputStream aStream, String anImageType) { - JAI.create("encode", scaledImage, aStream, anImageType, null); - } - - public byte[] getScaledData(String anImageType) { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - writeScaledData(outputStream, anImageType); - return outputStream.toByteArray(); - } - - public void writeScaledData(File aFile, String anImageType) throws MediaExc { - try { - writeScaledData(new BufferedOutputStream(new FileOutputStream(aFile),8192), anImageType); - } - catch (FileNotFoundException f) { - throw new MediaFailure(f); - } - } -} - - - - - - - - - - - - - - - - - - - - diff --git a/source/mir/misc/FileUtil.java b/source/mir/misc/FileUtil.java deleted file mode 100755 index 9226914b..00000000 --- a/source/mir/misc/FileUtil.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * 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.misc; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStreamWriter; -import java.io.Reader; -/** - * Hilfsklasse zum Mergen von Template und Daten - */ -public final class FileUtil { - /** - * Privater Construktor to avoid accidental instantiation - */ - private FileUtil() { - } - - public static File getFile(String filename) throws IOException { - - try { - File f = null; - f = new File(filename); - File dir = new File(f.getParent()); - dir.mkdirs(); - - return f; - } - catch (Exception e) { - throw new IOException(e.toString()); - } - - } - - public static long write(File f, InputStream in) throws IOException { - - long size = 0; - - if (in != null) { - try { - BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(f),8192); - - // TODO get size with in.available() - int read; - byte[] buf = new byte[8 * 1024]; - while ( (read = in.read(buf)) != -1) { - out.write(buf, 0, read); - size += read; - } - - in.close(); - out.close(); - } - catch (IOException e) { - throw new IOException(e.toString()); - } - } - return size; - } - - public static long write(String filename, InputStream in) throws IOException { - - long size = 0; - - if (in != null) { - try { - File f = getFile(filename); - size = write(f, in); - } - catch (IOException e) { - throw new IOException(e.toString()); - } - } - return size; - } - - public static long write(String filename, Reader in, String encoding) throws IOException { - - long size = 0; - - if (in != null) { - try { - File f = getFile(filename); - FileOutputStream fOut = new FileOutputStream(f); - BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fOut, encoding),8192); - int read; - char[] cbuf = new char[8 * 1024]; - while ( (read = in.read(cbuf)) != -1) { - out.write(cbuf, 0, read); - size += read; - } - - out.close(); - in.close(); - } - catch (IOException e) { - throw new IOException(e.toString()); - } - } - return size; - } - - public static boolean read(String filename, byte out[]) throws IOException { - - File f = null; - f = new File(filename); - - if (f.exists()) { - try { - if (out.length != f.length()) - return false; - BufferedInputStream inStream; - inStream = new BufferedInputStream(new FileInputStream(f),8192); - inStream.read(out); - inStream.close(); - } - catch (IOException e) { - throw new IOException(e.toString()); - } - } - else { - return false; - } - return true; - } - - public static long getSize(String filename) { - File f = null; - f = new File(filename); - return f.exists() ? f.length():-1; - } - -} diff --git a/source/mir/misc/PDFUtil.java b/source/mir/misc/PDFUtil.java deleted file mode 100755 index 2e882525..00000000 --- a/source/mir/misc/PDFUtil.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * 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.misc; - -import java.io.BufferedOutputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; - -import javax.servlet.http.HttpServletResponse; - -import org.apache.fop.apps.Driver; -import org.apache.fop.apps.InputHandler; -import org.apache.fop.apps.XSLTInputHandler; -import org.apache.log.Hierarchy; -import org.apache.log.Logger; -import org.apache.log.Priority; -import org.xml.sax.XMLReader; - -public class PDFUtil { - - public static void makePDF(String foFilePath,Object pdfDestination,String stylesheetPath) throws Exception - { - try{ - Driver driver = new Driver(); - - //stupid logging that fop wants to use, needs to be changed - Hierarchy hierarchy = Hierarchy.getDefaultHierarchy(); - Logger fopLog=null; - fopLog = hierarchy.getLoggerFor("fop"); - fopLog.setPriority(Priority.WARN); - driver.setLogger(fopLog); - - driver.setRenderer(Driver.RENDER_PDF); - - File foFile=new File(foFilePath); - - String html2foStyleSheetPath; - html2foStyleSheetPath=stylesheetPath; - - File html2foStyleSheet=new File(html2foStyleSheetPath); - InputHandler inputHandler = - new XSLTInputHandler(foFile, html2foStyleSheet); - XMLReader parser = inputHandler.getParser(); - - if (pdfDestination instanceof String) { - String filePath = (String) pdfDestination; - driver.setOutputStream(new BufferedOutputStream(new FileOutputStream(filePath))); - driver.render(parser, inputHandler.getInputSource()); - } - else if (pdfDestination instanceof HttpServletResponse){ - HttpServletResponse res = (HttpServletResponse) pdfDestination; - ByteArrayOutputStream out = new ByteArrayOutputStream(); - driver.setOutputStream(out); - res.setContentType("application/pdf"); - - driver.render(parser, inputHandler.getInputSource()); - - byte[] content = out.toByteArray(); - res.setContentLength(content.length); - res.getOutputStream().write(content); - res.getOutputStream().flush(); - } - else { - throw new Exception("I'm sorry but I don't know how to output a pdf to an object of type" + pdfDestination.getClass().getName()); - } - } - - catch (Exception ex){ - throw(ex); - } - } -} - - - diff --git a/source/mir/producer/AbstractProducerNode.java b/source/mir/producer/AbstractProducerNode.java new file mode 100755 index 00000000..5ae90cab --- /dev/null +++ b/source/mir/producer/AbstractProducerNode.java @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2005 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, but you are not obligated to do so. + * If you do not wish to do so, delete this exception statement from your version. + */ +package mir.producer; + +import mir.log.LoggerWrapper; + +import java.util.Map; + +public abstract class AbstractProducerNode implements ProducerNode { + /** + * Compatibility construction + */ + public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerExc, ProducerFailure { + } + + public void produce(ProductionContext aProductionContext) throws ProducerExc, ProducerFailure { + produce(aProductionContext.getValueSet(), aProductionContext.getVerb(), aProductionContext.getLogger()); + } +} diff --git a/source/mir/producer/AssignmentProducerNode.java b/source/mir/producer/AssignmentProducerNode.java index 13c47934..d79e89b8 100755 --- a/source/mir/producer/AssignmentProducerNode.java +++ b/source/mir/producer/AssignmentProducerNode.java @@ -46,10 +46,13 @@ public class AssignmentProducerNode extends ProducerNodeDecorator { } public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure { + } + + public void produce(ProductionContext aProductionContext) throws ProducerExc, ProducerFailure { try { - ParameterExpander.setValueForKey(aValueMap, key, value); + ParameterExpander.setValueForKey(aProductionContext.getValueSet(), key, value); - super.produce(aValueMap, aVerb, aLogger); + super.produce(aProductionContext); } catch (Throwable t) { throw new ProducerFailure(t.getMessage(), t); diff --git a/source/mir/producer/BundleProducerNode.java b/source/mir/producer/BundleProducerNode.java index c86cdafb..fe68cd03 100755 --- a/source/mir/producer/BundleProducerNode.java +++ b/source/mir/producer/BundleProducerNode.java @@ -40,7 +40,7 @@ import mircoders.global.MirGlobal; /** * This producer node loads a bundle */ -public class BundleProducerNode implements ProducerNode { +public class BundleProducerNode extends AbstractProducerNode { private String key; private String bundleExpression; private String languageExpression; @@ -79,5 +79,4 @@ public class BundleProducerNode implements ProducerNode { languageExpression + " into key " + key + ": " + t.getMessage()); } } - } \ No newline at end of file diff --git a/source/mir/producer/CompositeProducerNode.java b/source/mir/producer/CompositeProducerNode.java index 63fe79e4..e7f33398 100755 --- a/source/mir/producer/CompositeProducerNode.java +++ b/source/mir/producer/CompositeProducerNode.java @@ -32,10 +32,11 @@ package mir.producer; import java.util.ArrayList; import java.util.Iterator; import java.util.List; -import java.util.Map; - -import mir.log.LoggerWrapper; +/** + * A ProducerNode that simply executes a + * list of ProducerNodes sequentially + */ public class CompositeProducerNode implements ProducerNode { private List subNodes; @@ -70,19 +71,18 @@ public class CompositeProducerNode implements ProducerNode { subNodes.clear(); } - protected boolean isAborted(Map aValueMap) { - Object producerValue = aValueMap.get(NodedProducer.PRODUCER_KEY); + protected boolean isAborted(ProductionContext aProductionContext) { return ( - (producerValue instanceof NodedProducer) && - ((NodedProducer) producerValue).getIsAborted()); + (aProductionContext.getProducer() instanceof NodedProducer) && + ((NodedProducer) aProductionContext.getProducer()).getIsAborted()); } - public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure, ProducerExc { + public void produce(ProductionContext aProductionContext) throws ProducerExc, ProducerFailure { Iterator i = subNodes.iterator(); - while (i.hasNext() && !isAborted(aValueMap)) { + while (i.hasNext() && !isAborted(aProductionContext)) { ProducerNode node = (ProducerNode) i.next(); - node.produce(aValueMap, aVerb, aLogger); + node.produce(aProductionContext); } } } \ No newline at end of file diff --git a/source/mir/producer/ConditionalProducerNode.java b/source/mir/producer/ConditionalProducerNode.java index 20fb3f1d..cb92e9da 100755 --- a/source/mir/producer/ConditionalProducerNode.java +++ b/source/mir/producer/ConditionalProducerNode.java @@ -29,11 +29,15 @@ */ package mir.producer; -import java.util.Map; - -import mir.log.LoggerWrapper; import mir.util.ParameterExpander; +/** + * ProducerNode for conditional constructs. + * + *

+ * Based on an expression that will be evaluated as a boolean, + * one of 2 subnodes will be called. + */ public class ConditionalProducerNode implements ProducerNode { private String condition; private ProducerNode trueNode; @@ -45,15 +49,18 @@ public class ConditionalProducerNode implements ProducerNode { falseNode = aFalseNode; } - public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure { + /** + * {@inheritDoc} + */ + public void produce(ProductionContext aProducerContext) throws ProducerExc, ProducerFailure { try { - if (ParameterExpander.evaluateBooleanExpression(aValueMap, condition)) { + if (ParameterExpander.evaluateBooleanExpression(aProducerContext.getValueSet(), condition)) { if (trueNode!=null) - trueNode.produce(aValueMap, aVerb, aLogger); + trueNode.produce(aProducerContext); } else { if (falseNode!=null) - falseNode.produce(aValueMap, aVerb, aLogger); + falseNode.produce(aProducerContext); } } catch (Exception e) { diff --git a/source/mir/producer/DirCopyingProducerNode.java b/source/mir/producer/DirCopyingProducerNode.java index 2eb3b084..8fc13e9c 100755 --- a/source/mir/producer/DirCopyingProducerNode.java +++ b/source/mir/producer/DirCopyingProducerNode.java @@ -33,10 +33,13 @@ import java.io.File; import java.util.Map; import mir.log.LoggerWrapper; -import mir.util.FileFunctions; +import mir.util.FileRoutines; import mir.util.ParameterExpander; -public class DirCopyingProducerNode implements ProducerNode { +/** + * + */ +public class DirCopyingProducerNode extends AbstractProducerNode { private String sourceExpression; private String destinationExpression; private File sourceBasePath; @@ -56,7 +59,7 @@ public class DirCopyingProducerNode implements ProducerNode { try { source = ParameterExpander.expandExpression( aValueMap, sourceExpression ); destination = ParameterExpander.expandExpression( aValueMap, destinationExpression ); - FileFunctions.copy( + FileRoutines.copy( new File(sourceBasePath, source), new File(destinationBasePath, destination)); aLogger.info(source + " copied into " + destination); diff --git a/source/mir/producer/EntityBatchingProducerNode.java b/source/mir/producer/EntityBatchingProducerNode.java index abdacc65..3e3a294f 100755 --- a/source/mir/producer/EntityBatchingProducerNode.java +++ b/source/mir/producer/EntityBatchingProducerNode.java @@ -29,31 +29,17 @@ */ package mir.producer; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - import mir.entity.adapter.EntityAdapterModel; import mir.entity.adapter.EntityIteratorAdapter; -import mir.log.LoggerWrapper; import mir.util.ParameterExpander; import mir.util.StringRoutines; +import java.util.*; + /** - *

Title: EntityBatchingProducerNode

- *

Description: - * This producer makes it possible to show articles in batches, like on archive - * pages. - * - * The order by clause should lead to a result set in reverse order: - * the first row will be the last entity in the last batch - *

- *

Copyright: Copyright (c) 2003

- *

Company:

- * @author not attributable - * @version 1.0 + * This producer makes it possible to show articles in batches, like on archive pages. + * The order by clause should lead to a result set in reverse order: + * the first row will be the last entity in the last batch */ public class EntityBatchingProducerNode implements ProducerNode { @@ -112,7 +98,7 @@ public class EntityBatchingProducerNode implements ProducerNode { ((NodedProducer) producerValue).getIsAborted()); } - public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure { + public void produce(ProductionContext aProducerContext) throws ProducerExc, ProducerFailure { int nrEntities; int nrBatchesAfterFirst; int nrEntitiesInFirstBatch; @@ -131,15 +117,15 @@ public class EntityBatchingProducerNode implements ProducerNode { int minNrEntitiesInFirstBatch; try { - nrBatchesToProcess = ParameterExpander.evaluateIntegerExpressionWithDefault( aValueMap, nrBatchesToProcessExpression, -1 ); + nrBatchesToProcess = ParameterExpander.evaluateIntegerExpressionWithDefault(aProducerContext.getValueSet(), nrBatchesToProcessExpression, -1); - expandedWhereClause = ParameterExpander.expandExpression( aValueMap, whereClause ); - expandedOrderByClause = ParameterExpander.expandExpression( aValueMap, orderByClause ); + expandedWhereClause = ParameterExpander.expandExpression( aProducerContext.getValueSet(), whereClause ); + expandedOrderByClause = ParameterExpander.expandExpression( aProducerContext.getValueSet(), orderByClause ); - nrEntitiesToSkip = ParameterExpander.evaluateIntegerExpression( aValueMap, nrEntitiesToSkipExpression); - nrEntitiesPerBatch = ParameterExpander.evaluateIntegerExpression( aValueMap, nrEntitiesPerBatchExpression); - minNrEntitiesInFirstBatch = ParameterExpander.evaluateIntegerExpression( aValueMap, minNrEntitiesInFirstBatchExpression); - List extraTableList = StringRoutines.splitString(ParameterExpander.expandExpression( aValueMap, extraTables).trim(), ","); + nrEntitiesToSkip = ParameterExpander.evaluateIntegerExpression( aProducerContext.getValueSet(), nrEntitiesToSkipExpression); + nrEntitiesPerBatch = ParameterExpander.evaluateIntegerExpression( aProducerContext.getValueSet(), nrEntitiesPerBatchExpression); + minNrEntitiesInFirstBatch = ParameterExpander.evaluateIntegerExpression( aProducerContext.getValueSet(), minNrEntitiesInFirstBatchExpression); + List extraTableList = StringRoutines.splitString(ParameterExpander.expandExpression( aProducerContext.getValueSet(), extraTables).trim(), ","); batchesData = new ArrayList(); batchLocations = new ArrayList(); @@ -168,14 +154,14 @@ public class EntityBatchingProducerNode implements ProducerNode { } batchData = new HashMap(); - ParameterExpander.setValueForKey(aValueMap, batchInfoKey, batchData); + ParameterExpander.setValueForKey(aProducerContext.getValueSet(), batchInfoKey, batchData); batchData.put("all", batchesData); batchData.put("first", batchesData.get(0)); batchData.put("last", batchesData.get(batchesData.size()-1)); batchData.put("count", new Integer(batchesData.size())); - if (batchListSubNode!=null && (!isAborted(aValueMap))) { - batchListSubNode.produce(aValueMap, aVerb, aLogger); + if (batchListSubNode!=null && (!isAborted(aProducerContext.getValueSet()))) { + batchListSubNode.produce(aProducerContext); } if (nrBatchesToProcess<0 || nrBatchesToProcess>nrBatchesAfterFirst+1) { @@ -183,7 +169,7 @@ public class EntityBatchingProducerNode implements ProducerNode { } if (batchSubNode!=null) { - for (i=0; iA NodedProducer is the root of a tree of ProducerNodes.

* *

There used to be a time when there were Producers that weren't * NodedProducers, however they have been phased out.

*/ + public class NodedProducer implements Producer { private ProducerNode rootNode; - private String verb; - private Map baseValues; private boolean isAborted; private boolean isFinished; protected final static String PRODUCER_KEY = "$producer"; - public NodedProducer( ProducerNode aRootNode, String aVerb, Map aBaseValues) { + public NodedProducer(ProducerNode aRootNode) { rootNode = aRootNode; - verb = aVerb; - baseValues = aBaseValues; isAborted = false; } - public boolean produce( LoggerWrapper aLogger ) throws ProducerFailure, ProducerExc { - Map valueMap; - - valueMap = new HashMap(); - valueMap.putAll(baseValues); - valueMap.put(PRODUCER_KEY, this); - - rootNode.produce(valueMap, verb, aLogger); + public boolean execute(ProductionContext aProductionContext) throws ProducerFailure, ProducerExc { + rootNode.produce(aProductionContext); synchronized(this) { isFinished=true; + return !isAborted; } } - public void abort() { + public void abort(ProductionContext aContext) { synchronized(this) { if (!isFinished) isAborted=true; @@ -81,10 +69,4 @@ public class NodedProducer implements Producer { return isAborted; } } - - public boolean getIsFinished() { - synchronized(this) { - return isFinished; - } - } } diff --git a/source/mir/producer/Producer.java b/source/mir/producer/Producer.java index 4b284619..75312a7a 100755 --- a/source/mir/producer/Producer.java +++ b/source/mir/producer/Producer.java @@ -29,9 +29,7 @@ */ package mir.producer; -import mir.log.LoggerWrapper; - -/** +/** *

A Producer is a set of tasks, scripted in xml. Producers allow * mir installations to have their own actions that can be called for * instance when a new article is posted. Originally producers were @@ -53,18 +51,16 @@ import mir.log.LoggerWrapper; * the Producer interface). When the Producer is executed, the * "produce" methods of each node are recursively called, effectively * executing the program as it was scripted

- * - * */ public interface Producer { /** - * - * - * @param aLogger - * @return false if aborted,true if not - * @throws ProducerFailure - * @throws ProducerExc + * Execute the producer + */ + public boolean execute(ProductionContext aContext) throws ProducerFailure, ProducerExc; + + /** + * Abort the execution of the producer. Will be called from a different + * thread and implementations should take this into account. */ - public boolean produce( LoggerWrapper aLogger ) throws ProducerFailure, ProducerExc; - public void abort(); + public void abort(ProductionContext aContext); } diff --git a/source/mir/producer/ProducerExc.java b/source/mir/producer/ProducerExc.java index c6129f86..93772fee 100755 --- a/source/mir/producer/ProducerExc.java +++ b/source/mir/producer/ProducerExc.java @@ -35,4 +35,8 @@ public class ProducerExc extends Exc { public ProducerExc(String aMessage) { super(aMessage); } + + public ProducerExc(String aMessage, Throwable aCause) { + super(aMessage, aCause); + } } diff --git a/source/mir/producer/ProducerFactory.java b/source/mir/producer/ProducerFactory.java index dc8d7712..61d6763f 100755 --- a/source/mir/producer/ProducerFactory.java +++ b/source/mir/producer/ProducerFactory.java @@ -32,6 +32,9 @@ package mir.producer; import java.util.List; import java.util.Map; +/** + * + */ public interface ProducerFactory { public interface ProducerVerb { String getName(); @@ -54,7 +57,7 @@ public interface ProducerFactory { public Producer makeProducer(String aVerb, Map aStartingValues) throws ProducerFailure, ProducerExc; /** - * The set of pre-defined verbs. Returns a list of {@link ProducerVerb}s + * The set of pre-defined verbs. Returns a List of {@link ProducerVerb}s */ public List verbs(); } diff --git a/source/mir/producer/ProducerFailure.java b/source/mir/producer/ProducerFailure.java index 48728130..aa1a52b1 100755 --- a/source/mir/producer/ProducerFailure.java +++ b/source/mir/producer/ProducerFailure.java @@ -32,8 +32,6 @@ package mir.producer; import multex.Failure; public class ProducerFailure extends Failure { - - public ProducerFailure(String msg,Throwable cause) { super(msg,cause); } diff --git a/source/mir/producer/ProducerNode.java b/source/mir/producer/ProducerNode.java index 2e0f7c8f..d9502dec 100755 --- a/source/mir/producer/ProducerNode.java +++ b/source/mir/producer/ProducerNode.java @@ -29,18 +29,12 @@ */ package mir.producer; -import java.util.Map; - -import mir.log.LoggerWrapper; - /** - * A ProducerNode is an atom of a noded producer factory. - * + * A ProducerNode forms a building block of a noded producer factory. */ public interface ProducerNode { /** - * Perform the operations of the producer node, based on a verb and a value set. - * The supplied logger object should be used for any logging. + * Perform the operations of the producer node, using the {@link ProductionContext}. */ - public void produce(Map aValueSet, String aVerb, LoggerWrapper aLogger) throws ProducerExc, ProducerFailure; + public void produce(ProductionContext aProductionContext) throws ProducerExc, ProducerFailure; } \ No newline at end of file diff --git a/source/mir/producer/ProducerNodeDecorator.java b/source/mir/producer/ProducerNodeDecorator.java index 747d9ee5..52011f0e 100755 --- a/source/mir/producer/ProducerNodeDecorator.java +++ b/source/mir/producer/ProducerNodeDecorator.java @@ -29,26 +29,22 @@ */ package mir.producer; -import java.util.Map; - -import mir.log.LoggerWrapper; - -public class ProducerNodeDecorator implements ProducerNode { +public abstract class ProducerNodeDecorator implements ProducerNode { private ProducerNode slave; protected ProducerNodeDecorator(ProducerNode aSlave) { slave = aSlave; } - protected boolean isAborted(Map aValueMap) { - Object producerValue = aValueMap.get(NodedProducer.PRODUCER_KEY); + protected boolean isAborted(ProductionContext aProductionContext) { return ( - (producerValue instanceof NodedProducer) && - ((NodedProducer) producerValue).getIsAborted()); + (aProductionContext.getProducer() instanceof NodedProducer) && + ((NodedProducer) aProductionContext.getProducer()).getIsAborted()); } - public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure, ProducerExc { - if (slave!=null) - slave.produce(aValueMap, aVerb, aLogger); + public void produce(ProductionContext aProductionContext) throws ProducerExc, ProducerFailure { + if (slave!=null) { + slave.produce(aProductionContext); + } } } \ No newline at end of file diff --git a/source/mir/producer/ProductionContext.java b/source/mir/producer/ProductionContext.java new file mode 100755 index 00000000..76cce0d2 --- /dev/null +++ b/source/mir/producer/ProductionContext.java @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2005 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, but you are not obligated to do so. + * If you do not wish to do so, delete this exception statement from your version. + */ +package mir.producer; + +import mir.log.LoggerWrapper; + +import java.util.Map; + +/** + * ProductionContext incorporates all facilities available + * to a producer during production + */ +public interface ProductionContext { + ProducerFactory getFactory(); + Producer getProducer(); + String getVerb(); + LoggerWrapper getLogger(); + Map getValueSet(); + // ProductionSpace getProductionSpace(); +} diff --git a/source/mir/producer/RDFAggregatorProducerNode.java b/source/mir/producer/RDFAggregatorProducerNode.java index 02ce1596..14377e98 100755 --- a/source/mir/producer/RDFAggregatorProducerNode.java +++ b/source/mir/producer/RDFAggregatorProducerNode.java @@ -34,27 +34,22 @@ import java.util.Map; import mir.log.LoggerWrapper; import mir.rss.RSSAggregator; -import mir.util.ExceptionFunctions; +import mir.util.ExceptionRoutines; import mir.util.ParameterExpander; -public class RDFAggregatorProducerNode implements ProducerNode { +public class RDFAggregatorProducerNode extends AbstractProducerNode { private String key; private String source; - private String order; - private String filter; - public RDFAggregatorProducerNode(String aKey, String aSource, String anOrder, String aFilter) { + public RDFAggregatorProducerNode(String aKey, String aSource) { key = aKey; source=aSource; - order=anOrder; - filter=aFilter; } public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure { try { aLogger.debug(source); String evaluatedKey = ParameterExpander.expandExpression( aValueMap, key ); - String evaluatedOrder = ParameterExpander.expandExpression( aValueMap, order ); Object evaluatedSource = ParameterExpander.evaluateExpression( aValueMap, source ); Object aggregator = aValueMap.get(evaluatedKey); @@ -80,7 +75,7 @@ public class RDFAggregatorProducerNode implements ProducerNode { throw new ProducerExc("RSSAggregator expected, " + aggregator.toString() + " found"); } catch (Throwable t) { - Throwable s = ExceptionFunctions.traceCauseException(t); + Throwable s = ExceptionRoutines.traceCauseException(t); aLogger.error("Error while aggregating RDF data: " + s.getClass().getName()+","+ s.getMessage()); } } diff --git a/source/mir/producer/RSSProducerNode.java b/source/mir/producer/RSSProducerNode.java index fa2bef15..29ee973e 100755 --- a/source/mir/producer/RSSProducerNode.java +++ b/source/mir/producer/RSSProducerNode.java @@ -35,10 +35,10 @@ import mir.log.LoggerWrapper; import mir.rss.RSS091Reader; import mir.rss.RSSData; import mir.rss.RSSReader; -import mir.util.ExceptionFunctions; +import mir.util.ExceptionRoutines; import mir.util.ParameterExpander; -public class RSSProducerNode implements ProducerNode { +public class RSSProducerNode extends AbstractProducerNode { private String key; private String url; private String version; @@ -89,8 +89,7 @@ public class RSSProducerNode implements ProducerNode { ParameterExpander.setValueForKey(aValueMap, expandedKey, rssData); } catch (Throwable t) { - Throwable s = ExceptionFunctions.traceCauseException(t); - aLogger.error("Error while processing RSS data: " + s.getClass().getName()+","+ s.getMessage()); + aLogger.warn("Error while processing RSS data", t); } } } \ No newline at end of file diff --git a/source/mir/producer/ValuesMapProducerNode.java b/source/mir/producer/ValuesMapProducerNode.java deleted file mode 100755 index e0a4ffcf..00000000 --- a/source/mir/producer/ValuesMapProducerNode.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * 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.producer; - -import java.util.Map; - -import mir.log.LoggerWrapper; - -public class ValuesMapProducerNode extends ProducerNodeDecorator { - private String key; - private String bundleIdentifier; - private Map map; - - public ValuesMapProducerNode(Map aMap, ProducerNode aSubNode) { - super(aSubNode); - } - - public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure { - try { - aValueMap.putAll(map); - - super.produce(aValueMap, aVerb, aLogger); - } - catch (Throwable t) { - throw new ProducerFailure(t.getMessage(), t); - } - } -} \ No newline at end of file diff --git a/source/mir/producer/reader/DefaultProducerNodeBuilders.java b/source/mir/producer/reader/DefaultProducerNodeBuilders.java index e0c80249..86429c30 100755 --- a/source/mir/producer/reader/DefaultProducerNodeBuilders.java +++ b/source/mir/producer/reader/DefaultProducerNodeBuilders.java @@ -1040,11 +1040,9 @@ public class DefaultProducerNodeBuilders { public static class RDFAggregatorProducerNodeBuilder extends AbstractProducerNodeBuilder { private final static String RDF_AGGREGATOR_KEY_ATTRIBUTE = KEY_ATTRIBUTE; private final static String RDF_AGGREGATOR_SOURCE_ATTRIBUTE = "source"; - private final static String RDF_AGGREGATOR_ORDER_ATTRIBUTE = ORDER_ATTRIBUTE; - private final static String RDF_AGGREGATOR_FILTER_ATTRIBUTE = "filter"; private final static String[] RDF_AGGREGATOR_REQUIRED_ATTRIBUTES = { RDF_AGGREGATOR_KEY_ATTRIBUTE, RDF_AGGREGATOR_SOURCE_ATTRIBUTE }; - private final static String[] RDF_AGGREGATOR_OPTIONAL_ATTRIBUTES = { RDF_AGGREGATOR_ORDER_ATTRIBUTE, RDF_AGGREGATOR_FILTER_ATTRIBUTE }; + private final static String[] RDF_AGGREGATOR_OPTIONAL_ATTRIBUTES = { }; private final static String[] RDF_AGGREGATOR_SUBNODES = { }; private String key; @@ -1061,12 +1059,10 @@ public class DefaultProducerNodeBuilders { key = (String) anAttributes.get( RDF_AGGREGATOR_KEY_ATTRIBUTE ); source = (String) anAttributes.get( RDF_AGGREGATOR_SOURCE_ATTRIBUTE ); - order = XMLReaderTool.getStringAttributeWithDefault(anAttributes, RDF_AGGREGATOR_SOURCE_ATTRIBUTE, ""); - filter = XMLReaderTool.getStringAttributeWithDefault(anAttributes, RDF_AGGREGATOR_FILTER_ATTRIBUTE, ""); } public ProducerNode constructNode() { - return new RDFAggregatorProducerNode(key, source, order, filter); + return new RDFAggregatorProducerNode(key, source); } } diff --git a/source/mir/producer/reader/ProducerConfigReader.java b/source/mir/producer/reader/ProducerConfigReader.java index d39fbee0..3b106898 100755 --- a/source/mir/producer/reader/ProducerConfigReader.java +++ b/source/mir/producer/reader/ProducerConfigReader.java @@ -43,7 +43,7 @@ import mir.producer.CompositeProducerNode; import mir.producer.ProducerFactory; import mir.producer.ProducerNode; import mir.producer.SimpleProducerVerb; -import mir.util.ExceptionFunctions; +import mir.util.ExceptionRoutines; import mir.util.xml.XMLParserEngine; import mir.util.xml.XMLParserExc; import mir.util.xml.XMLParserFailure; @@ -65,7 +65,7 @@ public class ProducerConfigReader { } catch (Throwable e) { - Throwable root = ExceptionFunctions.traceCauseException(e); + Throwable root = ExceptionRoutines.traceCauseException(e); if ((root instanceof XMLParserExc) && ((XMLParserExc) root).getHasLocation()) { XMLParserExc f = (XMLParserExc) root; @@ -83,7 +83,7 @@ public class ProducerConfigReader { } catch (Throwable e) { - Throwable root = ExceptionFunctions.traceCauseException(e); + Throwable root = ExceptionRoutines.traceCauseException(e); if ((root instanceof XMLParserExc) && ((XMLParserExc) root).getHasLocation()) { XMLParserExc f = (XMLParserExc) root; diff --git a/source/mir/producer/reader/ScriptedProducerFactory.java b/source/mir/producer/reader/ScriptedProducerFactory.java index e870733c..9e7b8253 100755 --- a/source/mir/producer/reader/ScriptedProducerFactory.java +++ b/source/mir/producer/reader/ScriptedProducerFactory.java @@ -83,7 +83,7 @@ public class ScriptedProducerFactory implements ProducerFactory { rootNode.addSubNode(verbNode); rootNode.addSubNode(body); - return new NodedProducer(rootNode, aVerb, aStartingValues); + return new NodedProducer(rootNode); } public List verbs() { diff --git a/source/mir/producer/reader/ScriptedProducerNode.java b/source/mir/producer/reader/ScriptedProducerNode.java index aa080524..0f256785 100755 --- a/source/mir/producer/reader/ScriptedProducerNode.java +++ b/source/mir/producer/reader/ScriptedProducerNode.java @@ -29,15 +29,16 @@ */ package mir.producer.reader; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import mir.log.LoggerWrapper; import mir.producer.ProducerExc; import mir.producer.ProducerFailure; import mir.producer.ProducerNode; +import mir.producer.ProductionContext; import mir.util.ParameterExpander; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + /** *

A ScriptedProducerNode is a ProducerNode which is defined in * producers.xml file by the <nodedefinition> statement.

@@ -63,11 +64,13 @@ public class ScriptedProducerNode implements ProducerNode { nodeParameterValues.putAll(aNodeParameterValues); } - public void produce(Map aValues, String aVerb, LoggerWrapper aLogger) throws ProducerFailure, ProducerExc { + public void produce(ProductionContext aProductionContext) throws ProducerFailure, ProducerExc { try { Map oldValues = new HashMap(); - ScriptedProducerNodeTool.saveMapValues(oldValues, aValues, definition.getStringParameters().keySet()); - ScriptedProducerNodeTool.saveMapValues(oldValues, aValues, definition.getIntegerParameters().keySet()); + ScriptedProducerNodeTool.saveMapValues(oldValues, + aProductionContext.getValueSet(), definition.getStringParameters().keySet()); + ScriptedProducerNodeTool.saveMapValues(oldValues, + aProductionContext.getValueSet(), definition.getIntegerParameters().keySet()); try { Iterator i = stringParameterValues.entrySet().iterator(); @@ -75,7 +78,9 @@ public class ScriptedProducerNode implements ProducerNode { Map.Entry entry = (Map.Entry) i.next(); if (entry.getValue() instanceof String) { - aValues.put(entry.getKey(), ParameterExpander.expandExpression(aValues, (String) entry.getValue())); + aProductionContext.getValueSet().put(entry.getKey(), + ParameterExpander.expandExpression(aProductionContext.getValueSet(), + (String) entry.getValue())); } } @@ -85,25 +90,27 @@ public class ScriptedProducerNode implements ProducerNode { Map.Entry entry = (Map.Entry) i.next(); if (entry.getValue() instanceof String) { - aValues.put(entry.getKey(), ParameterExpander.evaluateExpression(aValues, (String) entry.getValue())); + aProductionContext.getValueSet().put(entry.getKey(), + ParameterExpander.evaluateExpression(aProductionContext.getValueSet(), (String) entry.getValue())); } } - ScriptedProducerNodeTool.pushNodeParameterValues(aValues, definition.getName(), nodeParameterValues); + ScriptedProducerNodeTool.pushNodeParameterValues(aProductionContext.getValueSet(), + definition.getName(), nodeParameterValues); try { - definition.getBody().produce(aValues, aVerb, aLogger); + definition.getBody().produce(aProductionContext); } finally { - ScriptedProducerNodeTool.popNodeParameterValues(aValues, definition.getName()); + ScriptedProducerNodeTool.popNodeParameterValues(aProductionContext.getValueSet(), definition.getName()); } } finally { - ScriptedProducerNodeTool.restoreMapValues(aValues, definition.getIntegerParameters().keySet(), oldValues); - ScriptedProducerNodeTool.restoreMapValues(aValues, definition.getStringParameters().keySet(), oldValues); + ScriptedProducerNodeTool.restoreMapValues(aProductionContext.getValueSet(), definition.getIntegerParameters().keySet(), oldValues); + ScriptedProducerNodeTool.restoreMapValues(aProductionContext.getValueSet(), definition.getStringParameters().keySet(), oldValues); } } catch (Exception e) { - aLogger.error("Scripted producer node " + definition.getName() + " caused an exception: " + e.getMessage()); + aProductionContext.getLogger().error("Scripted producer node " + definition.getName() + " caused an exception", e); } } diff --git a/source/mir/producer/reader/ScriptedProducerNodeDefinition.java b/source/mir/producer/reader/ScriptedProducerNodeDefinition.java index 62a796d6..cf2015b7 100755 --- a/source/mir/producer/reader/ScriptedProducerNodeDefinition.java +++ b/source/mir/producer/reader/ScriptedProducerNodeDefinition.java @@ -29,18 +29,9 @@ */ package mir.producer.reader; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; -import java.util.Stack; - -import mir.log.LoggerWrapper; -import mir.producer.CompositeProducerNode; -import mir.producer.ProducerExc; -import mir.producer.ProducerFailure; -import mir.producer.ProducerNode; +import mir.producer.*; + +import java.util.*; public class ScriptedProducerNodeDefinition { private Map integerParameters; // name -> default value @@ -129,7 +120,6 @@ public class ScriptedProducerNodeDefinition { return result; } - protected static class NodeParameterProducerNode implements ProducerNode { private String parameterName; private String definitionName; @@ -139,16 +129,17 @@ public class ScriptedProducerNodeDefinition { parameterName = aParameterName; } - public void produce(Map aValues, String aVerb, LoggerWrapper aLogger) throws ProducerExc, ProducerFailure { + public void produce(ProductionContext aProductionContext) throws ProducerExc, ProducerFailure { ProducerNode producerNode; - Map runTimeData = (Map) ((Map) aValues.get(SCRIPTED_PRODUCERNODE_RUNTIMEDATA_KEY)).get(definitionName); + Map runTimeData = (Map) ((Map) aProductionContext.getValueSet().get(SCRIPTED_PRODUCERNODE_RUNTIMEDATA_KEY)).get(definitionName); Map parameters = (Map) ((Stack) runTimeData.get( SCRIPTED_PRODUCERNODE_RUNTIMESTACK_KEY )).peek(); producerNode = (ProducerNode) parameters.get(parameterName); - if (producerNode != null) - producerNode.produce(aValues, aVerb, aLogger); + if (producerNode != null) { + producerNode.produce(aProductionContext); + } } public Set buildVerbSet() { diff --git a/source/mir/rss/RSSReader.java b/source/mir/rss/RSSReader.java index faff1ea8..40db2173 100755 --- a/source/mir/rss/RSSReader.java +++ b/source/mir/rss/RSSReader.java @@ -35,7 +35,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import mir.util.DateTimeFunctions; +import mir.util.DateTimeRoutines; import mir.util.HTTPClientHelper; import mir.util.xml.XMLParserEngine; import mir.util.xml.XMLParserExc; @@ -455,7 +455,7 @@ public class RSSReader { try { String expression = data.toString().trim(); - return DateTimeFunctions.parseW3CDTFString(expression); + return DateTimeRoutines.parseW3CDTFString(expression); } catch (Throwable t) { diff --git a/source/mir/servlet/AbstractServlet.java b/source/mir/servlet/AbstractServlet.java index 1a90e763..d42d2e95 100755 --- a/source/mir/servlet/AbstractServlet.java +++ b/source/mir/servlet/AbstractServlet.java @@ -52,7 +52,7 @@ import mircoders.global.MirGlobal; * Copyright: Copyright (c) 2001, 2002 * Company: Mir-coders group * @author idfx, the Mir-coders group - * @version $Id: AbstractServlet.java,v 1.30.2.8 2005/03/26 11:26:24 zapata Exp $ + * @version $Id: AbstractServlet.java,v 1.30.2.9 2005/08/21 17:09:21 zapata Exp $ */ public abstract class AbstractServlet extends HttpServlet { @@ -157,7 +157,6 @@ public abstract class AbstractServlet extends HttpServlet { logger.info("Request now has encoding: " + aRequest.getCharacterEncoding()); } catch (NoSuchMethodException e) { - // TODO do something to support old servlet containers } catch (SecurityException e) { logger.error(e.getMessage()); diff --git a/source/mir/session/CommonsUploadedFileAdapter.java b/source/mir/session/CommonsUploadedFileAdapter.java index 8fcaf883..15c75bed 100755 --- a/source/mir/session/CommonsUploadedFileAdapter.java +++ b/source/mir/session/CommonsUploadedFileAdapter.java @@ -29,11 +29,13 @@ */ package mir.session; +import mir.util.IORoutines; +import org.apache.commons.fileupload.FileItem; + import java.io.File; import java.io.IOException; import java.io.InputStream; - -import org.apache.commons.fileupload.FileItem; +import java.io.OutputStream; public class CommonsUploadedFileAdapter implements UploadedFile { private FileItem fileItem; @@ -48,7 +50,15 @@ public class CommonsUploadedFileAdapter implements UploadedFile { fileItem.write(aFile); } catch (Exception e) { - e.printStackTrace(); + throw new SessionFailure(e); + } + } + + public void writeToStream(OutputStream aStream) throws SessionExc, SessionFailure { + try { + IORoutines.copyStream(fileItem.getInputStream(), aStream); + } + catch (Exception e) { throw new SessionFailure(e); } } diff --git a/source/mir/session/UploadedFile.java b/source/mir/session/UploadedFile.java index 89e54bdc..58eac873 100755 --- a/source/mir/session/UploadedFile.java +++ b/source/mir/session/UploadedFile.java @@ -31,6 +31,7 @@ package mir.session; import java.io.File; import java.io.InputStream; +import java.io.OutputStream; public interface UploadedFile { /** @@ -39,6 +40,11 @@ public interface UploadedFile { public void writeToFile(File aFile) throws SessionExc, SessionFailure; /** + * Writes the uploaded content to a file + */ + public void writeToStream(OutputStream aStream) throws SessionExc, SessionFailure; + + /** * Creates an InputStream to access the uploaded content */ public InputStream getInputStream() throws SessionExc, SessionFailure; diff --git a/source/mir/storage/Database.java b/source/mir/storage/Database.java index e8faec53..5550c87a 100755 --- a/source/mir/storage/Database.java +++ b/source/mir/storage/Database.java @@ -45,7 +45,9 @@ import org.postgresql.PGConnection; import org.postgresql.largeobject.LargeObject; import org.postgresql.largeobject.LargeObjectManager; -import java.io.*; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.InputStreamReader; import java.sql.*; import java.text.ParseException; import java.text.SimpleDateFormat; @@ -54,7 +56,7 @@ import java.util.*; /** * Implements database access. * - * @version $Id: Database.java,v 1.44.2.32 2005/04/16 18:37:23 zapata Exp $ + * @version $Id: Database.java,v 1.44.2.33 2005/08/21 17:09:21 zapata Exp $ * @author rk * @author Zapata * @@ -180,8 +182,6 @@ public class Database { break; case java.sql.Types.NUMERIC: - /** todo Numeric can be float or double depending upon - * metadata.getScale() / especially with oracle */ long outl = aResultSet.getLong(aFieldIndex); if (!aResultSet.wasNull()) { @@ -393,8 +393,6 @@ public class Database { anExtraTables=null; } - RecordRetriever retriever = new RecordRetriever(mainTable, aMainTablePrefix); - // check o_store for entitylist // only if no relational select if (anExtraTables==null) { @@ -411,6 +409,8 @@ public class Database { } } + RecordRetriever retriever = new RecordRetriever(mainTable, aMainTablePrefix); + EntityList result = null; Connection connection = null; @@ -577,7 +577,6 @@ public class Database { String returnId = null; Connection con = null; - PreparedStatement pstmt = null; try { String fieldName; @@ -610,7 +609,6 @@ public class Database { freeConnection(con); } - /** todo store entity in o_store */ return returnId; } @@ -707,7 +705,6 @@ public class Database { public boolean delete(String id) throws DatabaseFailure { invalidateObject(id); - /** todo could be prepared Statement */ int resultCode = 0; Connection connection = obtainConnection(); PreparedStatement statement = null; diff --git a/source/mir/storage/store/ObjectStore.java b/source/mir/storage/store/ObjectStore.java index 8c3a7f4a..3b4b6ce2 100755 --- a/source/mir/storage/store/ObjectStore.java +++ b/source/mir/storage/store/ObjectStore.java @@ -150,10 +150,6 @@ public class ObjectStore { */ public void invalidate(StoreContainerType stoc_type) { if (stoc_type != null) { - /* @todo invalidates too much: - * improvement: if instanceof StoreContainerEntity && EntityList - * then invalidate only StoreIdentifier matching the right table - */ StoreContainer stoc = getStoreContainerForStocType(stoc_type); if (stoc != null) stoc.invalidate(); diff --git a/source/mir/storage/store/StoreIdentifier.java b/source/mir/storage/store/StoreIdentifier.java index fab5a7d2..de65c7ac 100755 --- a/source/mir/storage/store/StoreIdentifier.java +++ b/source/mir/storage/store/StoreIdentifier.java @@ -48,9 +48,7 @@ import mir.entity.EntityList; import mir.log.LoggerWrapper; public class StoreIdentifier { - - /** @todo check if invalidating already to avoid deadlocks - * what about concurrency? */ + /** todo check if invalidating already to avoid deadlocks what about concurrency? */ private static ObjectStore o_store = ObjectStore.getInstance(); @@ -62,8 +60,6 @@ public class StoreIdentifier { protected LoggerWrapper logger = new LoggerWrapper("Database.ObjectStore"); - private StoreIdentifier() {} - public StoreIdentifier(StorableObject reference, int storeType, String uniqueIdentifier) { Class theClass; @@ -172,6 +168,4 @@ public class StoreIdentifier { id.append(" (" + timesUsed).append(") times used."); return id.toString(); } - - } \ No newline at end of file diff --git a/source/mir/storage/store/test/TestStore.java b/source/mir/storage/store/test/TestStore.java index 4f019955..b541757b 100755 --- a/source/mir/storage/store/test/TestStore.java +++ b/source/mir/storage/store/test/TestStore.java @@ -44,64 +44,61 @@ import mir.storage.store.StoreIdentifier; public class TestStore { - private static ObjectStore o_store = ObjectStore.getInstance(); + private static ObjectStore o_store = ObjectStore.getInstance(); - public TestStore() { + public TestStore() { - } + } - public static void main(String[] args) { - long startTime = System.currentTimeMillis(); - System.out.println("Starting testrun on ObjectStore..."); - TestStore testStore1 = new TestStore(); - testStore1.startTest(); - System.out.println("Finished testrun on ObjectStore. (" - + (System.currentTimeMillis() - startTime) + " ms)"); - } + public static void main(String[] args) { + long startTime = System.currentTimeMillis(); + System.out.println("Starting testrun on ObjectStore..."); + TestStore testStore1 = new TestStore(); + testStore1.startTest(); + System.out.println("Finished testrun on ObjectStore. (" + + (System.currentTimeMillis() - startTime) + " ms)"); + } - public void startTest() { + public void startTest() { - EntityC1 c1 = new EntityC1("1"); - o_store.add(c1.getStoreIdentifier()); - EntityC1 c12 = new EntityC1("2"); - o_store.add(c12.getStoreIdentifier()); + EntityC1 c1 = new EntityC1("1"); + o_store.add(c1.getStoreIdentifier()); + EntityC1 c12 = new EntityC1("2"); + o_store.add(c12.getStoreIdentifier()); o_store.add(c12.getStoreIdentifier()); // should not be added as it's there already EntityC2 c2; - for (int i=0; i<20; i++) { - c2 = new EntityC2(""+i); + for (int i = 0; i < 20; i++) { + c2 = new EntityC2("" + i); o_store.add(c2.getStoreIdentifier()); } // should contain only 10 - // test cycle: search in store +// test cycle: search in store - StorableObject reference; StoreIdentifier search_sid; + StorableObject reference; + StoreIdentifier search_sid; - // search for EntityC1 - search_sid=new StoreIdentifier(EntityC1.class,"1"); - reference=o_store.use(search_sid); - if (reference==null) +// search for EntityC1 + search_sid = new StoreIdentifier(EntityC1.class, "1"); + reference = o_store.use(search_sid); + if (reference == null) System.out.println("--- should have found" + search_sid.toString()); - search_sid=new StoreIdentifier(EntityC1.class,"A"); - reference=o_store.use(search_sid); - if (reference!=null) + search_sid = new StoreIdentifier(EntityC1.class, "A"); + reference = o_store.use(search_sid); + if (reference != null) System.out.println("--- should not have found" + search_sid.toString()); - search_sid=new StoreIdentifier(EntityC3.class,"1"); - reference=o_store.use(search_sid); - if (reference!=null) + search_sid = new StoreIdentifier(EntityC3.class, "1"); + reference = o_store.use(search_sid); + if (reference != null) System.out.println("--- should not have found" + search_sid.toString()); - // test cycle: invalidation */ - search_sid=new StoreIdentifier(EntityC1.class,"1"); +// test cycle: invalidation */ + search_sid = new StoreIdentifier(EntityC1.class, "1"); o_store.invalidate(search_sid); - System.out.println(o_store.toString()); - /** @todo compare values of store and state failed if values are not - * right*/ + System.out.println(o_store.toString()); - - - } + } } \ No newline at end of file diff --git a/source/mir/util/DateTimeFunctions.java b/source/mir/util/DateTimeFunctions.java index 4eff7486..95a81015 100755 --- a/source/mir/util/DateTimeFunctions.java +++ b/source/mir/util/DateTimeFunctions.java @@ -1,171 +1,36 @@ -/* - * 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.util; - -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -public class DateTimeFunctions { - /** - * private parameter-less constructor to prevent construction - */ -// private static LoggerWrapper logger = new LoggerWrapper("Utility.DatTimeFunctions"); - - - private DateTimeFunctions() { - } - - - private final static String SPACE = "[\t\n\r ]*"; - private final static String NUMBER = "[0-9]*"; - private final static String TWODIGITNUMBER = "[0-9][0-9]"; - private final static String FOURDIGITNUMBER = "[0-9][0-9][0-9][0-9]"; - private final static String FRACTION = "(\\.[0-9]*)|)"; - private final static String SIGN = "[-+]"; - private final static String TZD = "(Z|(+|-)([0-9][0-9]:[0-9][0-9]|[0-9][0-9][0-9][0-9]))"; - - /** - * Function to parse a W3CDTF formatted string. - * - * - * YYYY[-MM[-DD[Thh:mm[:ss[.s*]]TZD]]] - * - * @param aString - * @return Date - */ - public static Date parseW3CDTFString(String aString) throws UtilExc, UtilFailure { - try { - int year = 1; - int month = 1; - int day = 1; - int hour = 0; - int minute = 0; - int second = 0; - int millisecond = 0; - int houroffset = 0; - int minuteoffset = 0; - boolean negativeOffset = false; - - - SimpleParser parser = new SimpleParser(aString.trim()); - String part = parser.parse(NUMBER); - year=Integer.parseInt(part); - if (parser.parses("-")) { - parser.skip("-"); - part = parser.parse(NUMBER); - month = Integer.parseInt(part); - if (parser.parses("-")) { - parser.skip("-"); - part = parser.parse(NUMBER); - day = Integer.parseInt(part); - if (parser.parses("T")) { - parser.skip("T"); - part = parser.parse(NUMBER); - hour = Integer.parseInt(part); - parser.skip(":"); - part = parser.parse(NUMBER); - minute = Integer.parseInt(part); - if (parser.parses(":")) { - parser.skip(":"); - part = parser.parse(NUMBER); - second = Integer.parseInt(part); - if (parser.parses("\\.")) { - parser.skip("\\."); - part = parser.parse(NUMBER).substring(0,3); - while (part.length()<3) - part = "0" + part; - millisecond = Integer.parseInt(part); - } - } - if (parser.parses("Z|\\+|-")) { - String sign = parser.parse("Z|\\+|-"); - if (sign.equals("+") || sign.equals("-")) { - if (parser.parses(TWODIGITNUMBER)) { - part = parser.parse(TWODIGITNUMBER); - houroffset = Integer.parseInt(part); - } - if (parser.parses(":")) - parser.skip(":"); - if (parser.parses(TWODIGITNUMBER)) { - part = parser.parse(TWODIGITNUMBER); - minuteoffset = Integer.parseInt(part); - } - - if (sign.equals("-")) { - negativeOffset=true; - } - } - } - } - } - } - - - - String timeZoneID = "GMT"; - if (negativeOffset) - timeZoneID = timeZoneID+"-"; - timeZoneID = timeZoneID + StringRoutines.padStringLeft(Integer.toString(houroffset), 2, '0') + - StringRoutines.padStringLeft(Integer.toString(minuteoffset), 2, '0'); - - - TimeZone zone = TimeZone.getTimeZone(timeZoneID); - - Calendar calendar = new GregorianCalendar(zone); - calendar.set(year, month-1, day, hour, minute, second); - calendar.set(Calendar.MILLISECOND, millisecond); - - return calendar.getTime(); - } - catch (Throwable t) { -// logger.error("DateTimeFunctions.parseW3CDTFString: error parsing " + aString + ": " + t.toString()); - - throw new UtilFailure(t); - } - } - - public static String advancedDateFormat(String aFormat, Date aDate, String aTimeZone) { - return advancedDateFormat(aFormat, aDate, TimeZone.getTimeZone(aTimeZone)); - } - - public static String advancedDateFormat(String aFormat, Date aDate, TimeZone aTimeZone) { - SimpleDateFormat simpleFormat = new SimpleDateFormat(aFormat); - - simpleFormat.setTimeZone(aTimeZone); - return simpleFormat.format(aDate); - } - - public static String dateToSortableString(Date aDate) { - return advancedDateFormat("yyyyMMddHHmmss", aDate, "GMT"); - } -} \ No newline at end of file +/* + * Copyright (C) 2005 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, but you are not obligated to do so. + * If you do not wish to do so, delete this exception statement from your version. + */ +package mir.util; + +/** + * @deprecated Use mir.util.DateTimeRoutines instead + */ +public class DateTimeFunctions extends DateTimeRoutines { +} diff --git a/source/mir/util/DateTimeRoutines.java b/source/mir/util/DateTimeRoutines.java new file mode 100755 index 00000000..d3fc9418 --- /dev/null +++ b/source/mir/util/DateTimeRoutines.java @@ -0,0 +1,161 @@ +/* + * 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.util; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; + +public class DateTimeRoutines { + /** + * private parameter-less constructor to prevent construction + */ + protected DateTimeRoutines() { + } + + private final static String NUMBER = "[0-9]*"; + private final static String TWODIGITNUMBER = "[0-9][0-9]"; + + /** + * Function to parse a W3CDTF formatted string. + * + * + * YYYY[-MM[-DD[Thh:mm[:ss[.s*]]TZD]]] + * + * @param aString + * @return Date + */ + public static Date parseW3CDTFString(String aString) throws UtilExc, UtilFailure { + try { + int year = 1; + int month = 1; + int day = 1; + int hour = 0; + int minute = 0; + int second = 0; + int millisecond = 0; + int houroffset = 0; + int minuteoffset = 0; + boolean negativeOffset = false; + + + SimpleParser parser = new SimpleParser(aString.trim()); + String part = parser.parse(NUMBER); + year=Integer.parseInt(part); + if (parser.parses("-")) { + parser.skip("-"); + part = parser.parse(NUMBER); + month = Integer.parseInt(part); + if (parser.parses("-")) { + parser.skip("-"); + part = parser.parse(NUMBER); + day = Integer.parseInt(part); + if (parser.parses("T")) { + parser.skip("T"); + part = parser.parse(NUMBER); + hour = Integer.parseInt(part); + parser.skip(":"); + part = parser.parse(NUMBER); + minute = Integer.parseInt(part); + if (parser.parses(":")) { + parser.skip(":"); + part = parser.parse(NUMBER); + second = Integer.parseInt(part); + if (parser.parses("\\.")) { + parser.skip("\\."); + part = parser.parse(NUMBER).substring(0,3); + while (part.length()<3) + part = "0" + part; + millisecond = Integer.parseInt(part); + } + } + if (parser.parses("Z|\\+|-")) { + String sign = parser.parse("Z|\\+|-"); + if (sign.equals("+") || sign.equals("-")) { + if (parser.parses(TWODIGITNUMBER)) { + part = parser.parse(TWODIGITNUMBER); + houroffset = Integer.parseInt(part); + } + if (parser.parses(":")) + parser.skip(":"); + if (parser.parses(TWODIGITNUMBER)) { + part = parser.parse(TWODIGITNUMBER); + minuteoffset = Integer.parseInt(part); + } + + if (sign.equals("-")) { + negativeOffset=true; + } + } + } + } + } + } + + + String timeZoneID = "GMT"; + if (negativeOffset) + timeZoneID = timeZoneID+"-"; + timeZoneID = timeZoneID + StringRoutines.padStringLeft(Integer.toString(houroffset), 2, '0') + + StringRoutines.padStringLeft(Integer.toString(minuteoffset), 2, '0'); + + + TimeZone zone = TimeZone.getTimeZone(timeZoneID); + + Calendar calendar = new GregorianCalendar(zone); + calendar.set(year, month-1, day, hour, minute, second); + calendar.set(Calendar.MILLISECOND, millisecond); + + return calendar.getTime(); + } + catch (Throwable t) { +// logger.error("DateTimeFunctions.parseW3CDTFString: error parsing " + aString + ": " + t.toString()); + + throw new UtilFailure(t); + } + } + + public static String advancedDateFormat(String aFormat, Date aDate, String aTimeZone) { + return advancedDateFormat(aFormat, aDate, TimeZone.getTimeZone(aTimeZone)); + } + + public static String advancedDateFormat(String aFormat, Date aDate, TimeZone aTimeZone) { + SimpleDateFormat simpleFormat = new SimpleDateFormat(aFormat); + + simpleFormat.setTimeZone(aTimeZone); + return simpleFormat.format(aDate); + } + + public static String dateToSortableString(Date aDate) { + return advancedDateFormat("yyyyMMddHHmmss", aDate, "GMT"); + } +} \ No newline at end of file diff --git a/source/mir/util/ExceptionFunctions.java b/source/mir/util/ExceptionFunctions.java index 916692c7..aad178ca 100755 --- a/source/mir/util/ExceptionFunctions.java +++ b/source/mir/util/ExceptionFunctions.java @@ -1,89 +1,36 @@ -/* - * 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.util; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.lang.reflect.InvocationTargetException; - -import multex.Failure; - -import org.xml.sax.SAXException; - -/** - * - *

Title: ExceptionFunctions

- *

Description: Functions to assist handling and throwing exceptions

- *

Copyright: Copyright (c) 2003

- *

Company: Mir coders

- * @author Zapata - * @version 1.0 - */ - -public class ExceptionFunctions { - private ExceptionFunctions() { - } - - /** - * Traces an exception to it's root cause, using all known exception types that support - * cause exceptions. - * - * @return the cause (if found) - */ - - public static Throwable traceCauseException(Throwable anException) { - Throwable result = anException; - - while (true) { - if ((result instanceof Failure) && (((Failure) result).getCause()!=null)) { - result = ((Failure) result).getCause(); - } - else if ((result instanceof SAXException) && (((SAXException) result).getException()!=null)) { - result = ((SAXException) result).getException(); - } - else if ((result instanceof InvocationTargetException) && (((InvocationTargetException) result).getTargetException()!=null)) { - result = ((InvocationTargetException) result).getTargetException(); - } - else - break; - } - - return result; - } - - /** - * Prints an exception's stacktrace to a String - */ - public static String getStackTrace(Throwable aThrowable) { - StringWriter writer = new StringWriter(); - aThrowable.printStackTrace(new PrintWriter(writer)); - return writer.toString(); - } -} +/* + * Copyright (C) 2005 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, but you are not obligated to do so. + * If you do not wish to do so, delete this exception statement from your version. + */ +package mir.util; + +/** + * @deprecated Use mir.util.ExceptionRoutines instead + */ +public class ExceptionFunctions extends ExceptionRoutines { +} diff --git a/source/mir/util/ExceptionRoutines.java b/source/mir/util/ExceptionRoutines.java new file mode 100755 index 00000000..cf280506 --- /dev/null +++ b/source/mir/util/ExceptionRoutines.java @@ -0,0 +1,83 @@ +/* + * 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.util; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.lang.reflect.InvocationTargetException; + +import multex.Failure; + +import org.xml.sax.SAXException; + +/** + * Routines to assist in handling and throwing exceptions

+ */ + +public class ExceptionRoutines { + protected ExceptionRoutines() { + } + + /** + * Traces an exception to it's root cause, using all known exception types that support + * cause exceptions. + * + * @return the cause (if found) + */ + + public static Throwable traceCauseException(Throwable anException) { + Throwable result = anException; + + while (true) { + if ((result instanceof Failure) && (((Failure) result).getCause()!=null)) { + result = ((Failure) result).getCause(); + } + else if ((result instanceof SAXException) && (((SAXException) result).getException()!=null)) { + result = ((SAXException) result).getException(); + } + else if ((result instanceof InvocationTargetException) && (((InvocationTargetException) result).getTargetException()!=null)) { + result = ((InvocationTargetException) result).getTargetException(); + } + else + break; + } + + return result; + } + + /** + * Prints an exception's stacktrace to a String + */ + public static String getStackTrace(Throwable aThrowable) { + StringWriter writer = new StringWriter(); + aThrowable.printStackTrace(new PrintWriter(writer)); + return writer.toString(); + } +} diff --git a/source/mir/util/ExecFunctions.java b/source/mir/util/ExecFunctions.java index 5dc23f4e..bc6d8647 100755 --- a/source/mir/util/ExecFunctions.java +++ b/source/mir/util/ExecFunctions.java @@ -74,7 +74,7 @@ public class ExecFunctions { throw new IOException("command exit satus:"+exitStatus); } - byte [] result=FileFunctions.readFileIntoByteArray + byte [] result = FileRoutines.readFileIntoByteArray (commandOutput.getAbsolutePath()); commandOutput.delete(); return result; diff --git a/source/mir/util/FileFunctions.java b/source/mir/util/FileFunctions.java index a49c1498..7ade9aa2 100755 --- a/source/mir/util/FileFunctions.java +++ b/source/mir/util/FileFunctions.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2001, 2002 The Mir-coders group + * Copyright (C) 2005 The Mir-coders group * * This file is part of Mir. * @@ -29,205 +29,9 @@ */ package mir.util; -import gnu.regexp.RE; -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.FilenameFilter; -import java.io.IOException; -import java.io.InputStream; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -public class FileFunctions { - protected static final int FILE_COPY_BUFFER_SIZE = 65536; - - private FileFunctions() { - } - - public static void copyFile(File aSourceFile, File aDestinationFile) throws IOException { - BufferedInputStream inputStream; - BufferedOutputStream outputStream; - int nrBytesRead; - byte[] buffer = new byte[FILE_COPY_BUFFER_SIZE]; - - inputStream = new BufferedInputStream( - new FileInputStream(aSourceFile)); - try { - File directory = new File(aDestinationFile.getParent()); - if (directory!=null && !directory.exists()){ - directory.mkdirs(); - } - outputStream = new BufferedOutputStream( - new FileOutputStream(aDestinationFile),8192); - try { - do { - nrBytesRead = inputStream.read(buffer); - if (nrBytesRead>0) - outputStream.write(buffer, 0, nrBytesRead); - } - while (nrBytesRead>=0); - } - finally { - outputStream.close(); - } - } - finally { - inputStream.close(); - } - } - - public static void copyDirectory(File aSourceDirectory, File aDestinationDirectory) throws IOException { - int i; - File sourceFile; - File destinationFile; - File[] files = aSourceDirectory.listFiles(); - - if (!aDestinationDirectory.exists()) - aDestinationDirectory.mkdirs(); - - for (i=0; i0) { - outputStream.write(buffer, 0, count); - count=inputStream.read(buffer); - } - } - finally { - outputStream.close(); - inputStream.close(); - } - aSource.delete(); - } - } - - /** - * Reads the content of a file into a string - */ - public static String readFileIntoString(String fileName) - throws IOException - { - return new String(readFileIntoByteArray(fileName)); - } - /** - * Reads the content of a file into an array of bytes - */ - public static byte[] readFileIntoByteArray(String fileName) - throws IOException - { - FileInputStream input = new FileInputStream(fileName); - int size= input.available(); - byte result[]= new byte[size]; - input.read(result); - return result; - } - - public static class RegExpFileFilter implements FilenameFilter { - private RE expression; - - public RegExpFileFilter(String anExpression) { - try { - expression = new RE(anExpression); - } - catch (Throwable t) { - throw new RuntimeException(t.getMessage()); - } - } - - public boolean accept(File aDir, String aName) { - return expression.isMatch(aName) && !new File(aDir, aName).isDirectory(); - } - } - - public static class DirectoryFilter implements FilenameFilter { - public DirectoryFilter() { - } - - public boolean accept(File aDir, String aName) { - return new File(aDir, aName).isDirectory(); - } - } - - public static List getDirectoryContentsAsList(File aDirectory, FilenameFilter aFilter) { - Object[] contents = aDirectory.list(aFilter); - if (contents==null) - return Collections.EMPTY_LIST; - return Arrays.asList(contents); - } - - public static String getExtension(String aPath) { - int position = aPath.lastIndexOf('.'); - if (position>=0) { - return aPath.substring(position+1); - } - return ""; - } - - public static boolean isAbsolutePath(String aPath) { - return new File(aPath).isAbsolute(); - } - - public static File getAbsoluteOrRelativeFile(File aParentIfRelative, String aPath) { - if (isAbsolutePath(aPath)) { - return new File(aPath); - } - return new File(aParentIfRelative, aPath); - } -} +/** + * @deprecated Use mir.util.FileRoutines instead + */ +public class FileFunctions extends FileRoutines { +} \ No newline at end of file diff --git a/source/mir/util/FileMonitor.java b/source/mir/util/FileMonitor.java deleted file mode 100755 index 6e4f5315..00000000 --- a/source/mir/util/FileMonitor.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * 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.util; - -import java.io.File; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -public class FileMonitor { - private Map files; - - public FileMonitor() { - files = new HashMap(); - } - - public void addFile(File aFile) { - files.put(aFile, new Long(aFile.lastModified())); - } - - public void clear() { - files.clear(); - } - - public boolean hasChanged() { - Iterator i = files.entrySet().iterator(); - - while (i.hasNext()) { - Map.Entry entry = (Map.Entry) i.next(); - File file = (File) entry.getKey(); - Long lastModified = (Long) entry.getValue(); - - if (lastModified.longValue()!=file.lastModified()) - return true; - } - - return false; - } -} \ No newline at end of file diff --git a/source/mir/util/FileRoutines.java b/source/mir/util/FileRoutines.java new file mode 100755 index 00000000..4c414b0a --- /dev/null +++ b/source/mir/util/FileRoutines.java @@ -0,0 +1,270 @@ +/* + * 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.util; + +import gnu.regexp.RE; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FilenameFilter; +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class FileRoutines { + protected static final int FILE_COPY_BUFFER_SIZE = 65536; + + protected FileRoutines() { + } + + public static void copyFile(File aSourceFile, File aDestinationFile) throws IOException { + BufferedInputStream inputStream; + BufferedOutputStream outputStream; + int nrBytesRead; + byte[] buffer = new byte[FILE_COPY_BUFFER_SIZE]; + + inputStream = new BufferedInputStream( + new FileInputStream(aSourceFile)); + try { + File directory = new File(aDestinationFile.getParent()); + if (directory!=null && !directory.exists()){ + directory.mkdirs(); + } + outputStream = new BufferedOutputStream( + new FileOutputStream(aDestinationFile),8192); + try { + do { + nrBytesRead = inputStream.read(buffer); + if (nrBytesRead>0) + outputStream.write(buffer, 0, nrBytesRead); + } + while (nrBytesRead>=0); + } + finally { + outputStream.close(); + } + } + finally { + inputStream.close(); + } + } + + public static void copyDirectory(File aSourceDirectory, File aDestinationDirectory) throws IOException { + int i; + File sourceFile; + File destinationFile; + File[] files = aSourceDirectory.listFiles(); + + if (!aDestinationDirectory.exists()) + aDestinationDirectory.mkdirs(); + + for (i=0; i0) { + outputStream.write(buffer, 0, count); + count=inputStream.read(buffer); + } + } + finally { + outputStream.close(); + inputStream.close(); + } + aSource.delete(); + } + } + + public static class RegExpFileFilter implements FilenameFilter { + private RE expression; + + public RegExpFileFilter(String anExpression) { + try { + expression = new RE(anExpression); + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + + public boolean accept(File aDir, String aName) { + return expression.isMatch(aName) && !new File(aDir, aName).isDirectory(); + } + } + + public static class DirectoryFilter implements FilenameFilter { + public DirectoryFilter() { + } + + public boolean accept(File aDir, String aName) { + return new File(aDir, aName).isDirectory(); + } + } + + /** + * Return all files in a directory + * + * @param aDirectory The directory to list + * @param aFilter the filter to apply to files + * @return a List of filenames of type String + */ + public static List getDirectoryContentsAsList(File aDirectory, FilenameFilter aFilter) { + Object[] contents = aDirectory.list(aFilter); + + if (contents==null) { + return Collections.EMPTY_LIST; + } + + return Arrays.asList(contents); + } + + /** + * Return the extension of a path. (e.g. getExtension("example.txt") will + * return "txt" + */ + public static String getExtension(String aPath) { + int position = aPath.lastIndexOf('.'); + if (position>=0) { + return aPath.substring(position+1); + } + return ""; + } + + public static boolean isAbsolutePath(String aPath) { + return new File(aPath).isAbsolute(); + } + + /** + * Transforms an absolute or relative path into an absolute + * {@link File}. + * + * @param aBasePath The base path to use for relative paths + * @param aPath The path to transform + * @return An absolute representation of the supplied path + */ + public static File getAbsoluteOrRelativeFile(File aBasePath, String aPath) { + if (isAbsolutePath(aPath)) { + return new File(aPath); + } + + return new File(aBasePath, aPath); + } + + /** + * Reads the content of a file into a string + * + * TODO: The encoding to be used has not been taken into account: the routine now + * assumes the file is encoded according to the JVM/platform default + */ + public static String readFileIntoString(String fileName) throws IOException { + return new String(readFileIntoByteArray(fileName)); + } + + /** + * Reads the content of a file into an array of bytes + * + * TODO: add a loop: {@link java.io.InputStream#available()} is not + * the total number of bytes left in the stream, but depends on buffering + * etc. + */ + public static byte[] readFileIntoByteArray(String fileName) throws IOException { + InputStream input = new FileInputStream(fileName); + int size= input.available(); + byte result[] = new byte[size]; + input.read(result); + + return result; + } + + /** + * Creates all parent directories of a file if they do not exist + */ + public static void createParentDirectories(File aFile) { + if (aFile.getParentFile()!=null && !aFile.getParentFile().exists()) { + aFile.getParentFile().mkdirs(); + } + } + } \ No newline at end of file diff --git a/source/mir/util/GeneratorDateTimeFunctions.java b/source/mir/util/GeneratorDateTimeFunctions.java index 36a8d11a..234db7d0 100755 --- a/source/mir/util/GeneratorDateTimeFunctions.java +++ b/source/mir/util/GeneratorDateTimeFunctions.java @@ -65,14 +65,16 @@ public class GeneratorDateTimeFunctions { SimpleDateFormat dateFormat = new SimpleDateFormat( (String) (aParameters.get(1))); String timezoneString = ""; - if (aParameters.size()>2) + if (aParameters.size()>2) { timezoneString = (String) aParameters.get(2); - else + } + else { timezoneString = defaultTimezone; + } TimeZone timezone = null; try { - timezone = TimeZone.getTimeZone(defaultTimezone); + timezone = TimeZone.getTimeZone(timezoneString); } catch (Throwable t) { } diff --git a/source/mir/util/IORoutines.java b/source/mir/util/IORoutines.java new file mode 100755 index 00000000..5f04a970 --- /dev/null +++ b/source/mir/util/IORoutines.java @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2005 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, but you are not obligated to do so. + * If you do not wish to do so, delete this exception statement from your version. + */ +package mir.util; + +import java.io.OutputStream; +import java.io.InputStream; +import java.io.IOException; + +public class IORoutines { + private IORoutines() { + } + + public static void copyStream(InputStream anInputStream, OutputStream anOutputStream) throws IOException { + byte[] buffer = new byte[128*1024]; + int size; + + while ( (size = anInputStream.read(buffer)) > 0) { + anOutputStream.write(buffer, 0, size); + } + } + + public static void writeStream(String aData, String anEncoding, OutputStream anOutputStream) throws IOException { + anOutputStream.write(aData.getBytes(anEncoding)); + } + +} diff --git a/source/mir/util/NullWriter.java b/source/mir/util/NullWriter.java deleted file mode 100755 index fe8f0b6d..00000000 --- a/source/mir/util/NullWriter.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * 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.util; - -import java.io.Writer; - -public class NullWriter extends Writer { - - public NullWriter() { - } - - public void close() { - } - - public void flush() { - } - - public void write(char[] cbuf, int off, int len) { - } -} \ No newline at end of file diff --git a/source/mir/util/Translate.java b/source/mir/util/Translate.java deleted file mode 100755 index 90785dae..00000000 --- a/source/mir/util/Translate.java +++ /dev/null @@ -1,593 +0,0 @@ -// todo....figure out what license changes need to be made here... - -// HTMLParser Library v1_3_20030511 - A java-based parser for HTML -// Copyright (C) Dec 31, 2000 Somik Raha -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; either -// version 2.1 of the License, or (at your option) any later version. -// -// This library 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 -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -// -// For any questions or suggestions, you can write to me at : -// Email :somik@industriallogic.com -// -// Postal Address : -// Somik Raha -// Extreme Programmer & Coach -// Industrial Logic Corporation -// 2583 Cedar Street, Berkeley, -// CA 94708, USA -// Website : http://www.industriallogic.com -// -// This class was contributed by -// Derrick Oswald -// - -package mir.util; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -/** - * Translate numeric character references and character entity references to unicode characters. - * Based on tables found at - * http://www.w3.org/TR/REC-html40/sgml/entities.html - *

Note: Do not edit! This class is created by the Generate class. - *

Typical usage: - *

- *      String s = Translate.decode (getTextFromHtmlPage ());
- * 
- * @author Derrick Oswald - */ -public class Translate -{ - /** - * Table mapping entity reference kernel to character. - *

String->Character - */ - protected static Map refChar; - static - { - refChar = new HashMap(1000); - - // Portions © International Organization for Standardization 1986 - // Permission to copy in any form is granted for use with - // conforming SGML systems and applications as defined in - // ISO 8879, provided this notice is included in all copies. - // Character entity set. Typical invocation: - // - // %HTMLlat1; - refChar.put ("nbsp", new Character ('\u00a0')); // no-break space = non-breaking space, U+00A0 ISOnum - refChar.put ("iexcl", new Character ('\u00a1')); // inverted exclamation mark, U+00A1 ISOnum - refChar.put ("cent", new Character ('\u00a2')); // cent sign, U+00A2 ISOnum - refChar.put ("pound", new Character ('\u00a3')); // pound sign, U+00A3 ISOnum - refChar.put ("curren", new Character ('\u00a4')); // currency sign, U+00A4 ISOnum - refChar.put ("yen", new Character ('\u00a5')); // yen sign = yuan sign, U+00A5 ISOnum - refChar.put ("brvbar", new Character ('\u00a6')); // broken bar = broken vertical bar, U+00A6 ISOnum - refChar.put ("sect", new Character ('\u00a7')); // section sign, U+00A7 ISOnum - refChar.put ("uml", new Character ('\u00a8')); // diaeresis = spacing diaeresis, U+00A8 ISOdia - refChar.put ("copy", new Character ('\u00a9')); // copyright sign, U+00A9 ISOnum - refChar.put ("ordf", new Character ('\u00aa')); // feminine ordinal indicator, U+00AA ISOnum - refChar.put ("laquo", new Character ('\u00ab')); // left-pointing double angle quotation mark = left pointing guillemet, U+00AB ISOnum - refChar.put ("not", new Character ('\u00ac')); // not sign, U+00AC ISOnum - refChar.put ("shy", new Character ('\u00ad')); // soft hyphen = discretionary hyphen, U+00AD ISOnum - refChar.put ("reg", new Character ('\u00ae')); // registered sign = registered trade mark sign, U+00AE ISOnum - refChar.put ("macr", new Character ('\u00af')); // macron = spacing macron = overline = APL overbar, U+00AF ISOdia - refChar.put ("deg", new Character ('\u00b0')); // degree sign, U+00B0 ISOnum - refChar.put ("plusmn", new Character ('\u00b1')); // plus-minus sign = plus-or-minus sign, U+00B1 ISOnum - refChar.put ("sup2", new Character ('\u00b2')); // superscript two = superscript digit two = squared, U+00B2 ISOnum - refChar.put ("sup3", new Character ('\u00b3')); // superscript three = superscript digit three = cubed, U+00B3 ISOnum - refChar.put ("acute", new Character ('\u00b4')); // acute accent = spacing acute, U+00B4 ISOdia - refChar.put ("micro", new Character ('\u00b5')); // micro sign, U+00B5 ISOnum - refChar.put ("para", new Character ('\u00b6')); // pilcrow sign = paragraph sign, U+00B6 ISOnum - refChar.put ("middot", new Character ('\u00b7')); // middle dot = Georgian comma = Greek middle dot, U+00B7 ISOnum - refChar.put ("cedil", new Character ('\u00b8')); // cedilla = spacing cedilla, U+00B8 ISOdia - refChar.put ("sup1", new Character ('\u00b9')); // superscript one = superscript digit one, U+00B9 ISOnum - refChar.put ("ordm", new Character ('\u00ba')); // masculine ordinal indicator, U+00BA ISOnum - refChar.put ("raquo", new Character ('\u00bb')); // right-pointing double angle quotation mark = right pointing guillemet, U+00BB ISOnum - refChar.put ("frac14", new Character ('\u00bc')); // vulgar fraction one quarter = fraction one quarter, U+00BC ISOnum - refChar.put ("frac12", new Character ('\u00bd')); // vulgar fraction one half = fraction one half, U+00BD ISOnum - refChar.put ("frac34", new Character ('\u00be')); // vulgar fraction three quarters = fraction three quarters, U+00BE ISOnum - refChar.put ("iquest", new Character ('\u00bf')); // inverted question mark = turned question mark, U+00BF ISOnum - refChar.put ("Agrave", new Character ('\u00c0')); // latin capital letter A with grave = latin capital letter A grave, U+00C0 ISOlat1 - refChar.put ("Aacute", new Character ('\u00c1')); // latin capital letter A with acute, U+00C1 ISOlat1 - refChar.put ("Acirc", new Character ('\u00c2')); // latin capital letter A with circumflex, U+00C2 ISOlat1 - refChar.put ("Atilde", new Character ('\u00c3')); // latin capital letter A with tilde, U+00C3 ISOlat1 - refChar.put ("Auml", new Character ('\u00c4')); // latin capital letter A with diaeresis, U+00C4 ISOlat1 - refChar.put ("Aring", new Character ('\u00c5')); // latin capital letter A with ring above = latin capital letter A ring, U+00C5 ISOlat1 - refChar.put ("AElig", new Character ('\u00c6')); // latin capital letter AE = latin capital ligature AE, U+00C6 ISOlat1 - refChar.put ("Ccedil", new Character ('\u00c7')); // latin capital letter C with cedilla, U+00C7 ISOlat1 - refChar.put ("Egrave", new Character ('\u00c8')); // latin capital letter E with grave, U+00C8 ISOlat1 - refChar.put ("Eacute", new Character ('\u00c9')); // latin capital letter E with acute, U+00C9 ISOlat1 - refChar.put ("Ecirc", new Character ('\u00ca')); // latin capital letter E with circumflex, U+00CA ISOlat1 - refChar.put ("Euml", new Character ('\u00cb')); // latin capital letter E with diaeresis, U+00CB ISOlat1 - refChar.put ("Igrave", new Character ('\u00cc')); // latin capital letter I with grave, U+00CC ISOlat1 - refChar.put ("Iacute", new Character ('\u00cd')); // latin capital letter I with acute, U+00CD ISOlat1 - refChar.put ("Icirc", new Character ('\u00ce')); // latin capital letter I with circumflex, U+00CE ISOlat1 - refChar.put ("Iuml", new Character ('\u00cf')); // latin capital letter I with diaeresis, U+00CF ISOlat1 - refChar.put ("ETH", new Character ('\u00d0')); // latin capital letter ETH, U+00D0 ISOlat1 - refChar.put ("Ntilde", new Character ('\u00d1')); // latin capital letter N with tilde, U+00D1 ISOlat1 - refChar.put ("Ograve", new Character ('\u00d2')); // latin capital letter O with grave, U+00D2 ISOlat1 - refChar.put ("Oacute", new Character ('\u00d3')); // latin capital letter O with acute, U+00D3 ISOlat1 - refChar.put ("Ocirc", new Character ('\u00d4')); // latin capital letter O with circumflex, U+00D4 ISOlat1 - refChar.put ("Otilde", new Character ('\u00d5')); // latin capital letter O with tilde, U+00D5 ISOlat1 - refChar.put ("Ouml", new Character ('\u00d6')); // latin capital letter O with diaeresis, U+00D6 ISOlat1 - refChar.put ("times", new Character ('\u00d7')); // multiplication sign, U+00D7 ISOnum - refChar.put ("Oslash", new Character ('\u00d8')); // latin capital letter O with stroke = latin capital letter O slash, U+00D8 ISOlat1 - refChar.put ("Ugrave", new Character ('\u00d9')); // latin capital letter U with grave, U+00D9 ISOlat1 - refChar.put ("Uacute", new Character ('\u00da')); // latin capital letter U with acute, U+00DA ISOlat1 - refChar.put ("Ucirc", new Character ('\u00db')); // latin capital letter U with circumflex, U+00DB ISOlat1 - refChar.put ("Uuml", new Character ('\u00dc')); // latin capital letter U with diaeresis, U+00DC ISOlat1 - refChar.put ("Yacute", new Character ('\u00dd')); // latin capital letter Y with acute, U+00DD ISOlat1 - refChar.put ("THORN", new Character ('\u00de')); // latin capital letter THORN, U+00DE ISOlat1 - refChar.put ("szlig", new Character ('\u00df')); // latin small letter sharp s = ess-zed, U+00DF ISOlat1 - refChar.put ("agrave", new Character ('\u00e0')); // latin small letter a with grave = latin small letter a grave, U+00E0 ISOlat1 - refChar.put ("aacute", new Character ('\u00e1')); // latin small letter a with acute, U+00E1 ISOlat1 - refChar.put ("acirc", new Character ('\u00e2')); // latin small letter a with circumflex, U+00E2 ISOlat1 - refChar.put ("atilde", new Character ('\u00e3')); // latin small letter a with tilde, U+00E3 ISOlat1 - refChar.put ("auml", new Character ('\u00e4')); // latin small letter a with diaeresis, U+00E4 ISOlat1 - refChar.put ("aring", new Character ('\u00e5')); // latin small letter a with ring above = latin small letter a ring, U+00E5 ISOlat1 - refChar.put ("aelig", new Character ('\u00e6')); // latin small letter ae = latin small ligature ae, U+00E6 ISOlat1 - refChar.put ("ccedil", new Character ('\u00e7')); // latin small letter c with cedilla, U+00E7 ISOlat1 - refChar.put ("egrave", new Character ('\u00e8')); // latin small letter e with grave, U+00E8 ISOlat1 - refChar.put ("eacute", new Character ('\u00e9')); // latin small letter e with acute, U+00E9 ISOlat1 - refChar.put ("ecirc", new Character ('\u00ea')); // latin small letter e with circumflex, U+00EA ISOlat1 - refChar.put ("euml", new Character ('\u00eb')); // latin small letter e with diaeresis, U+00EB ISOlat1 - refChar.put ("igrave", new Character ('\u00ec')); // latin small letter i with grave, U+00EC ISOlat1 - refChar.put ("iacute", new Character ('\u00ed')); // latin small letter i with acute, U+00ED ISOlat1 - refChar.put ("icirc", new Character ('\u00ee')); // latin small letter i with circumflex, U+00EE ISOlat1 - refChar.put ("iuml", new Character ('\u00ef')); // latin small letter i with diaeresis, U+00EF ISOlat1 - refChar.put ("eth", new Character ('\u00f0')); // latin small letter eth, U+00F0 ISOlat1 - refChar.put ("ntilde", new Character ('\u00f1')); // latin small letter n with tilde, U+00F1 ISOlat1 - refChar.put ("ograve", new Character ('\u00f2')); // latin small letter o with grave, U+00F2 ISOlat1 - refChar.put ("oacute", new Character ('\u00f3')); // latin small letter o with acute, U+00F3 ISOlat1 - refChar.put ("ocirc", new Character ('\u00f4')); // latin small letter o with circumflex, U+00F4 ISOlat1 - refChar.put ("otilde", new Character ('\u00f5')); // latin small letter o with tilde, U+00F5 ISOlat1 - refChar.put ("ouml", new Character ('\u00f6')); // latin small letter o with diaeresis, U+00F6 ISOlat1 - refChar.put ("divide", new Character ('\u00f7')); // division sign, U+00F7 ISOnum - refChar.put ("oslash", new Character ('\u00f8')); // latin small letter o with stroke, = latin small letter o slash, U+00F8 ISOlat1 - refChar.put ("ugrave", new Character ('\u00f9')); // latin small letter u with grave, U+00F9 ISOlat1 - refChar.put ("uacute", new Character ('\u00fa')); // latin small letter u with acute, U+00FA ISOlat1 - refChar.put ("ucirc", new Character ('\u00fb')); // latin small letter u with circumflex, U+00FB ISOlat1 - refChar.put ("uuml", new Character ('\u00fc')); // latin small letter u with diaeresis, U+00FC ISOlat1 - refChar.put ("yacute", new Character ('\u00fd')); // latin small letter y with acute, U+00FD ISOlat1 - refChar.put ("thorn", new Character ('\u00fe')); // latin small letter thorn, U+00FE ISOlat1 - refChar.put ("yuml", new Character ('\u00ff')); // latin small letter y with diaeresis, U+00FF ISOlat1 - // Mathematical, Greek and Symbolic characters for HTML - // Character entity set. Typical invocation: - // - // %HTMLsymbol; - // Portions © International Organization for Standardization 1986: - // Permission to copy in any form is granted for use with - // conforming SGML systems and applications as defined in - // ISO 8879, provided this notice is included in all copies. - // Relevant ISO entity set is given unless names are newly introduced. - // New names (i.e., not in ISO 8879 list) do not clash with any - // existing ISO 8879 entity names. ISO 10646 character numbers - // are given for each character, in hex. CDATA values are decimal - // conversions of the ISO 10646 values and refer to the document - // character set. Names are ISO 10646 names. - // Latin Extended-B - refChar.put ("fnof", new Character ('\u0192')); // latin small f with hook = function = florin, U+0192 ISOtech - // Greek - refChar.put ("Alpha", new Character ('\u0391')); // greek capital letter alpha, U+0391 - refChar.put ("Beta", new Character ('\u0392')); // greek capital letter beta, U+0392 - refChar.put ("Gamma", new Character ('\u0393')); // greek capital letter gamma, U+0393 ISOgrk3 - refChar.put ("Delta", new Character ('\u0394')); // greek capital letter delta, U+0394 ISOgrk3 - refChar.put ("Epsilon", new Character ('\u0395')); // greek capital letter epsilon, U+0395 - refChar.put ("Zeta", new Character ('\u0396')); // greek capital letter zeta, U+0396 - refChar.put ("Eta", new Character ('\u0397')); // greek capital letter eta, U+0397 - refChar.put ("Theta", new Character ('\u0398')); // greek capital letter theta, U+0398 ISOgrk3 - refChar.put ("Iota", new Character ('\u0399')); // greek capital letter iota, U+0399 - refChar.put ("Kappa", new Character ('\u039a')); // greek capital letter kappa, U+039A - refChar.put ("Lambda", new Character ('\u039b')); // greek capital letter lambda, U+039B ISOgrk3 - refChar.put ("Mu", new Character ('\u039c')); // greek capital letter mu, U+039C - refChar.put ("Nu", new Character ('\u039d')); // greek capital letter nu, U+039D - refChar.put ("Xi", new Character ('\u039e')); // greek capital letter xi, U+039E ISOgrk3 - refChar.put ("Omicron", new Character ('\u039f')); // greek capital letter omicron, U+039F - refChar.put ("Pi", new Character ('\u03a0')); // greek capital letter pi, U+03A0 ISOgrk3 - refChar.put ("Rho", new Character ('\u03a1')); // greek capital letter rho, U+03A1 - // there is no Sigmaf, and no U+03A2 character either - refChar.put ("Sigma", new Character ('\u03a3')); // greek capital letter sigma, U+03A3 ISOgrk3 - refChar.put ("Tau", new Character ('\u03a4')); // greek capital letter tau, U+03A4 - refChar.put ("Upsilon", new Character ('\u03a5')); // greek capital letter upsilon, U+03A5 ISOgrk3 - refChar.put ("Phi", new Character ('\u03a6')); // greek capital letter phi, U+03A6 ISOgrk3 - refChar.put ("Chi", new Character ('\u03a7')); // greek capital letter chi, U+03A7 - refChar.put ("Psi", new Character ('\u03a8')); // greek capital letter psi, U+03A8 ISOgrk3 - refChar.put ("Omega", new Character ('\u03a9')); // greek capital letter omega, U+03A9 ISOgrk3 - refChar.put ("alpha", new Character ('\u03b1')); // greek small letter alpha, U+03B1 ISOgrk3 - refChar.put ("beta", new Character ('\u03b2')); // greek small letter beta, U+03B2 ISOgrk3 - refChar.put ("gamma", new Character ('\u03b3')); // greek small letter gamma, U+03B3 ISOgrk3 - refChar.put ("delta", new Character ('\u03b4')); // greek small letter delta, U+03B4 ISOgrk3 - refChar.put ("epsilon", new Character ('\u03b5')); // greek small letter epsilon, U+03B5 ISOgrk3 - refChar.put ("zeta", new Character ('\u03b6')); // greek small letter zeta, U+03B6 ISOgrk3 - refChar.put ("eta", new Character ('\u03b7')); // greek small letter eta, U+03B7 ISOgrk3 - refChar.put ("theta", new Character ('\u03b8')); // greek small letter theta, U+03B8 ISOgrk3 - refChar.put ("iota", new Character ('\u03b9')); // greek small letter iota, U+03B9 ISOgrk3 - refChar.put ("kappa", new Character ('\u03ba')); // greek small letter kappa, U+03BA ISOgrk3 - refChar.put ("lambda", new Character ('\u03bb')); // greek small letter lambda, U+03BB ISOgrk3 - refChar.put ("mu", new Character ('\u03bc')); // greek small letter mu, U+03BC ISOgrk3 - refChar.put ("nu", new Character ('\u03bd')); // greek small letter nu, U+03BD ISOgrk3 - refChar.put ("xi", new Character ('\u03be')); // greek small letter xi, U+03BE ISOgrk3 - refChar.put ("omicron", new Character ('\u03bf')); // greek small letter omicron, U+03BF NEW - refChar.put ("pi", new Character ('\u03c0')); // greek small letter pi, U+03C0 ISOgrk3 - refChar.put ("rho", new Character ('\u03c1')); // greek small letter rho, U+03C1 ISOgrk3 - refChar.put ("sigmaf", new Character ('\u03c2')); // greek small letter final sigma, U+03C2 ISOgrk3 - refChar.put ("sigma", new Character ('\u03c3')); // greek small letter sigma, U+03C3 ISOgrk3 - refChar.put ("tau", new Character ('\u03c4')); // greek small letter tau, U+03C4 ISOgrk3 - refChar.put ("upsilon", new Character ('\u03c5')); // greek small letter upsilon, U+03C5 ISOgrk3 - refChar.put ("phi", new Character ('\u03c6')); // greek small letter phi, U+03C6 ISOgrk3 - refChar.put ("chi", new Character ('\u03c7')); // greek small letter chi, U+03C7 ISOgrk3 - refChar.put ("psi", new Character ('\u03c8')); // greek small letter psi, U+03C8 ISOgrk3 - refChar.put ("omega", new Character ('\u03c9')); // greek small letter omega, U+03C9 ISOgrk3 - refChar.put ("thetasym", new Character ('\u03d1')); // greek small letter theta symbol, U+03D1 NEW - refChar.put ("upsih", new Character ('\u03d2')); // greek upsilon with hook symbol, U+03D2 NEW - refChar.put ("piv", new Character ('\u03d6')); // greek pi symbol, U+03D6 ISOgrk3 - // General Punctuation - refChar.put ("bull", new Character ('\u2022')); // bullet = black small circle, U+2022 ISOpub - // bullet is NOT the same as bullet operator, U+2219 - refChar.put ("hellip", new Character ('\u2026')); // horizontal ellipsis = three dot leader, U+2026 ISOpub - refChar.put ("prime", new Character ('\u2032')); // prime = minutes = feet, U+2032 ISOtech - refChar.put ("Prime", new Character ('\u2033')); // double prime = seconds = inches, U+2033 ISOtech - refChar.put ("oline", new Character ('\u203e')); // overline = spacing overscore, U+203E NEW - refChar.put ("frasl", new Character ('\u2044')); // fraction slash, U+2044 NEW - // Letterlike Symbols - refChar.put ("weierp", new Character ('\u2118')); // script capital P = power set = Weierstrass p, U+2118 ISOamso - refChar.put ("image", new Character ('\u2111')); // blackletter capital I = imaginary part, U+2111 ISOamso - refChar.put ("real", new Character ('\u211c')); // blackletter capital R = real part symbol, U+211C ISOamso - refChar.put ("trade", new Character ('\u2122')); // trade mark sign, U+2122 ISOnum - refChar.put ("alefsym", new Character ('\u2135')); // alef symbol = first transfinite cardinal, U+2135 NEW - // alef symbol is NOT the same as hebrew letter alef, - // U+05D0 although the same glyph could be used to depict both characters - // Arrows - refChar.put ("larr", new Character ('\u2190')); // leftwards arrow, U+2190 ISOnum - refChar.put ("uarr", new Character ('\u2191')); // upwards arrow, U+2191 ISOnum - refChar.put ("rarr", new Character ('\u2192')); // rightwards arrow, U+2192 ISOnum - refChar.put ("darr", new Character ('\u2193')); // downwards arrow, U+2193 ISOnum - refChar.put ("harr", new Character ('\u2194')); // left right arrow, U+2194 ISOamsa - refChar.put ("crarr", new Character ('\u21b5')); // downwards arrow with corner leftwards = carriage return, U+21B5 NEW - refChar.put ("lArr", new Character ('\u21d0')); // leftwards double arrow, U+21D0 ISOtech - // ISO 10646 does not say that lArr is the same as the 'is implied by' arrow - // but also does not have any other character for that function. So ? lArr can - // be used for 'is implied by' as ISOtech suggests - refChar.put ("uArr", new Character ('\u21d1')); // upwards double arrow, U+21D1 ISOamsa - refChar.put ("rArr", new Character ('\u21d2')); // rightwards double arrow, U+21D2 ISOtech - // ISO 10646 does not say this is the 'implies' character but does not have - // another character with this function so ? - // rArr can be used for 'implies' as ISOtech suggests - refChar.put ("dArr", new Character ('\u21d3')); // downwards double arrow, U+21D3 ISOamsa - refChar.put ("hArr", new Character ('\u21d4')); // left right double arrow, U+21D4 ISOamsa - // Mathematical Operators - refChar.put ("forall", new Character ('\u2200')); // for all, U+2200 ISOtech - refChar.put ("part", new Character ('\u2202')); // partial differential, U+2202 ISOtech - refChar.put ("exist", new Character ('\u2203')); // there exists, U+2203 ISOtech - refChar.put ("empty", new Character ('\u2205')); // empty set = null set = diameter, U+2205 ISOamso - refChar.put ("nabla", new Character ('\u2207')); // nabla = backward difference, U+2207 ISOtech - refChar.put ("isin", new Character ('\u2208')); // element of, U+2208 ISOtech - refChar.put ("notin", new Character ('\u2209')); // not an element of, U+2209 ISOtech - refChar.put ("ni", new Character ('\u220b')); // contains as member, U+220B ISOtech - // should there be a more memorable name than 'ni'? - refChar.put ("prod", new Character ('\u220f')); // n-ary product = product sign, U+220F ISOamsb - // prod is NOT the same character as U+03A0 'greek capital letter pi' though - // the same glyph might be used for both - refChar.put ("sum", new Character ('\u2211')); // n-ary sumation, U+2211 ISOamsb - // sum is NOT the same character as U+03A3 'greek capital letter sigma' - // though the same glyph might be used for both - refChar.put ("minus", new Character ('\u2212')); // minus sign, U+2212 ISOtech - refChar.put ("lowast", new Character ('\u2217')); // asterisk operator, U+2217 ISOtech - refChar.put ("radic", new Character ('\u221a')); // square root = radical sign, U+221A ISOtech - refChar.put ("prop", new Character ('\u221d')); // proportional to, U+221D ISOtech - refChar.put ("infin", new Character ('\u221e')); // infinity, U+221E ISOtech - refChar.put ("ang", new Character ('\u2220')); // angle, U+2220 ISOamso - refChar.put ("and", new Character ('\u2227')); // logical and = wedge, U+2227 ISOtech - refChar.put ("or", new Character ('\u2228')); // logical or = vee, U+2228 ISOtech - refChar.put ("cap", new Character ('\u2229')); // intersection = cap, U+2229 ISOtech - refChar.put ("cup", new Character ('\u222a')); // union = cup, U+222A ISOtech - refChar.put ("int", new Character ('\u222b')); // integral, U+222B ISOtech - refChar.put ("there4", new Character ('\u2234')); // therefore, U+2234 ISOtech - refChar.put ("sim", new Character ('\u223c')); // tilde operator = varies with = similar to, U+223C ISOtech - // tilde operator is NOT the same character as the tilde, U+007E, - // although the same glyph might be used to represent both - refChar.put ("cong", new Character ('\u2245')); // approximately equal to, U+2245 ISOtech - refChar.put ("asymp", new Character ('\u2248')); // almost equal to = asymptotic to, U+2248 ISOamsr - refChar.put ("ne", new Character ('\u2260')); // not equal to, U+2260 ISOtech - refChar.put ("equiv", new Character ('\u2261')); // identical to, U+2261 ISOtech - refChar.put ("le", new Character ('\u2264')); // less-than or equal to, U+2264 ISOtech - refChar.put ("ge", new Character ('\u2265')); // greater-than or equal to, U+2265 ISOtech - refChar.put ("sub", new Character ('\u2282')); // subset of, U+2282 ISOtech - refChar.put ("sup", new Character ('\u2283')); // superset of, U+2283 ISOtech - // note that nsup, 'not a superset of, U+2283' is not covered by the Symbol - // font encoding and is not included. Should it be, for symmetry? - // It is in ISOamsn - refChar.put ("nsub", new Character ('\u2284')); // not a subset of, U+2284 ISOamsn - refChar.put ("sube", new Character ('\u2286')); // subset of or equal to, U+2286 ISOtech - refChar.put ("supe", new Character ('\u2287')); // superset of or equal to, U+2287 ISOtech - refChar.put ("oplus", new Character ('\u2295')); // circled plus = direct sum, U+2295 ISOamsb - refChar.put ("otimes", new Character ('\u2297')); // circled times = vector product, U+2297 ISOamsb - refChar.put ("perp", new Character ('\u22a5')); // up tack = orthogonal to = perpendicular, U+22A5 ISOtech - refChar.put ("sdot", new Character ('\u22c5')); // dot operator, U+22C5 ISOamsb - // dot operator is NOT the same character as U+00B7 middle dot - // Miscellaneous Technical - refChar.put ("lceil", new Character ('\u2308')); // left ceiling = apl upstile, U+2308 ISOamsc - refChar.put ("rceil", new Character ('\u2309')); // right ceiling, U+2309 ISOamsc - refChar.put ("lfloor", new Character ('\u230a')); // left floor = apl downstile, U+230A ISOamsc - refChar.put ("rfloor", new Character ('\u230b')); // right floor, U+230B ISOamsc - refChar.put ("lang", new Character ('\u2329')); // left-pointing angle bracket = bra, U+2329 ISOtech - // lang is NOT the same character as U+003C 'less than' - // or U+2039 'single left-pointing angle quotation mark' - refChar.put ("rang", new Character ('\u232a')); // right-pointing angle bracket = ket, U+232A ISOtech - // rang is NOT the same character as U+003E 'greater than' - // or U+203A 'single right-pointing angle quotation mark' - // Geometric Shapes - refChar.put ("loz", new Character ('\u25ca')); // lozenge, U+25CA ISOpub - // Miscellaneous Symbols - refChar.put ("spades", new Character ('\u2660')); // black spade suit, U+2660 ISOpub - // black here seems to mean filled as opposed to hollow - refChar.put ("clubs", new Character ('\u2663')); // black club suit = shamrock, U+2663 ISOpub - refChar.put ("hearts", new Character ('\u2665')); // black heart suit = valentine, U+2665 ISOpub - refChar.put ("diams", new Character ('\u2666')); // black diamond suit, U+2666 ISOpub - // Special characters for HTML - // Character entity set. Typical invocation: - // - // %HTMLspecial; - // Portions © International Organization for Standardization 1986: - // Permission to copy in any form is granted for use with - // conforming SGML systems and applications as defined in - // ISO 8879, provided this notice is included in all copies. - // Relevant ISO entity set is given unless names are newly introduced. - // New names (i.e., not in ISO 8879 list) do not clash with any - // existing ISO 8879 entity names. ISO 10646 character numbers - // are given for each character, in hex. CDATA values are decimal - // conversions of the ISO 10646 values and refer to the document - // character set. Names are ISO 10646 names. - // C0 Controls and Basic Latin - refChar.put ("quot", new Character ('\u0022')); // quotation mark = APL quote, U+0022 ISOnum - refChar.put ("amp", new Character ('\u0026')); // ampersand, U+0026 ISOnum - refChar.put ("lt", new Character ('\u003c')); // less-than sign, U+003C ISOnum - refChar.put ("gt", new Character ('\u003e')); // greater-than sign, U+003E ISOnum - // Latin Extended-A - refChar.put ("OElig", new Character ('\u0152')); // latin capital ligature OE, U+0152 ISOlat2 - refChar.put ("oelig", new Character ('\u0153')); // latin small ligature oe, U+0153 ISOlat2 - // ligature is a misnomer, this is a separate character in some languages - refChar.put ("Scaron", new Character ('\u0160')); // latin capital letter S with caron, U+0160 ISOlat2 - refChar.put ("scaron", new Character ('\u0161')); // latin small letter s with caron, U+0161 ISOlat2 - refChar.put ("Yuml", new Character ('\u0178')); // latin capital letter Y with diaeresis, U+0178 ISOlat2 - // Spacing Modifier Letters - refChar.put ("circ", new Character ('\u02c6')); // modifier letter circumflex accent, U+02C6 ISOpub - refChar.put ("tilde", new Character ('\u02dc')); // small tilde, U+02DC ISOdia - // General Punctuation - refChar.put ("ensp", new Character ('\u2002')); // en space, U+2002 ISOpub - refChar.put ("emsp", new Character ('\u2003')); // em space, U+2003 ISOpub - refChar.put ("thinsp", new Character ('\u2009')); // thin space, U+2009 ISOpub - refChar.put ("zwnj", new Character ('\u200c')); // zero width non-joiner, U+200C NEW RFC 2070 - refChar.put ("zwj", new Character ('\u200d')); // zero width joiner, U+200D NEW RFC 2070 - refChar.put ("lrm", new Character ('\u200e')); // left-to-right mark, U+200E NEW RFC 2070 - refChar.put ("rlm", new Character ('\u200f')); // right-to-left mark, U+200F NEW RFC 2070 - refChar.put ("ndash", new Character ('\u2013')); // en dash, U+2013 ISOpub - refChar.put ("mdash", new Character ('\u2014')); // em dash, U+2014 ISOpub - refChar.put ("lsquo", new Character ('\u2018')); // left single quotation mark, U+2018 ISOnum - refChar.put ("rsquo", new Character ('\u2019')); // right single quotation mark, U+2019 ISOnum - refChar.put ("sbquo", new Character ('\u201a')); // single low-9 quotation mark, U+201A NEW - refChar.put ("ldquo", new Character ('\u201c')); // left double quotation mark, U+201C ISOnum - refChar.put ("rdquo", new Character ('\u201d')); // right double quotation mark, U+201D ISOnum - refChar.put ("bdquo", new Character ('\u201e')); // double low-9 quotation mark, U+201E NEW - refChar.put ("dagger", new Character ('\u2020')); // dagger, U+2020 ISOpub - refChar.put ("Dagger", new Character ('\u2021')); // double dagger, U+2021 ISOpub - refChar.put ("permil", new Character ('\u2030')); // per mille sign, U+2030 ISOtech - refChar.put ("lsaquo", new Character ('\u2039')); // single left-pointing angle quotation mark, U+2039 ISO proposed - // lsaquo is proposed but not yet ISO standardized - refChar.put ("rsaquo", new Character ('\u203a')); // single right-pointing angle quotation mark, U+203A ISO proposed - // rsaquo is proposed but not yet ISO standardized - refChar.put ("euro", new Character ('\u20ac')); // euro sign, U+20AC NEW - } - - /** - * Table mapping character to entity reference kernel. - *

Character->String - */ - protected static Map charRefTable; - static - { - charRefTable = new HashMap (refChar.size ()); - Iterator iterator = refChar.keySet ().iterator (); - while (iterator.hasNext ()) - { - String key = (String)iterator.next (); - Character character = (Character)refChar.get (key); - charRefTable.put (character, key); - } - } - - /** - * Private constructor. - * This class is fully static and thread safe. - */ - private Translate () - { - } - - /** - * Convert a reference to a unicode character. - * Convert a single numeric character reference or character entity reference - * to a unicode character. - * @param string The string to convert. Of the form &xxxx; or &#xxxx; with - * or without the leading ampersand or trailing semi-colon. - * @return The converted character or '\0' (zero) if the string is an - * invalid reference. - */ - public static char convertToChar (String string) - { - int length; - Character item; - char ret; - - ret = 0; - - length = string.length (); - if (0 < length) - { - if ('&' == string.charAt (0)) - { - string = string.substring (1); - length--; - } - if (0 < length) - { - if (';' == string.charAt (length - 1)) - string = string.substring (0, --length); - if (0 < length) - { - if ('#' == string.charAt (0)) - try - { - ret = (char)Integer.parseInt (string.substring (1)); - } - catch (NumberFormatException nfe) - { - /* failed conversion, return 0 */ - } - else - { - item = (Character)refChar.get (string); - if (null != item) - ret = item.charValue (); - } - } - } - } - - return (ret); - } - - /** - * Decode a string containing references. - * Change all numeric character reference and character entity references - * to unicode characters. - * @param string The string to translate. - */ - public static String decode (String string) - { - int index; - int length; - int amp; - int semi; - String code; - char character; - StringBuffer ret; - ret = new StringBuffer (string.length ()); - index = 0; - length = string.length (); - while ((index < length) && (-1 != (amp = string.indexOf ('&', index)))) - { - ret.append (string.substring (index, amp)); - index = amp + 1; - if (amp < length - 1) - { - semi = string.indexOf (';', amp); - if (-1 != semi) - code = string.substring (amp, semi + 1); - else - code = string.substring (amp); - if (0 != (character = convertToChar (code))) - index += code.length () - 1; - else - character = '&'; - } - else - character = '&'; - ret.append (character); - } - if (index < length) - ret.append (string.substring (index)); - return (ret.toString ()); - } - - /** - * Convert a character to a character entity reference. - * Convert a unicode character to a character entity reference of - * the form &xxxx;. - * @param character The character to convert. - * @return The converted character or null if the character - * is not one of the known entity references. - */ - public static String convertToString (Character character) - { - StringBuffer buffer; - String ret; - if (null != (ret = (String)charRefTable.get (character))) - { - buffer = new StringBuffer (ret.length () + 2); - buffer.append ('&'); - buffer.append (ret); - buffer.append (';'); - ret = buffer.toString (); - } - return (ret); - } - - /** - * Convert a character to a numeric character reference. - * Convert a unicode character to a numeric character reference of - * the form &#xxxx;. - * @param character The character to convert. - * @return The converted character. - */ - public static String convertToString (int character) - { - StringBuffer ret; - ret = new StringBuffer (13); /* � */ - ret.append ("&#"); - ret.append (character); - ret.append (';'); - return (ret.toString ()); - } - - /** - * Encode a string to use references. - * Change all characters that are not ASCII to their numeric character - * reference or character entity reference. - * This implementation is inefficient, allocating a new - * Character for each character in the string, - * but this class is primarily intended to decode strings - * so efficiency and speed in the encoding was not a priority. - * @param string The string to translate. - */ - public static String encode (String string) - { - int length; - char c; - Character character; - String value; - StringBuffer ret; - ret = new StringBuffer (string.length () * 6); - length = string.length (); - for (int i = 0; i < length; i++) - { - c = string.charAt (i); - character = new Character (c); - if (null != (value = convertToString (character))) - ret.append (value); - else if (!((c > 0x001F) && (c < 0x007F))) - { - value = convertToString (c); - ret.append (value); - } - else - ret.append (character); - } - return (ret.toString ()); - } -} diff --git a/source/mir/util/xml/XMLParserEngine.java b/source/mir/util/xml/XMLParserEngine.java index 9b4d9286..8202e0e6 100755 --- a/source/mir/util/xml/XMLParserEngine.java +++ b/source/mir/util/xml/XMLParserEngine.java @@ -42,7 +42,7 @@ import java.util.HashMap; import java.util.Map; import java.util.Stack; -import mir.util.ExceptionFunctions; +import mir.util.ExceptionRoutines; import mir.util.xml.html.XMLHTMLParserProvider; public class XMLParserEngine { @@ -136,7 +136,7 @@ public class XMLParserEngine { provider.parse(aReader, runner); } catch (Throwable e) { - Throwable t = ExceptionFunctions.traceCauseException(e); + Throwable t = ExceptionRoutines.traceCauseException(e); if (t instanceof XMLParserExc && runner.getLocator()!=null) { ((XMLParserExc) t).setLocation(runner.getLocator().getLineNr(), runner.getLocator().getColumnNr()); diff --git a/source/mir/util/xml/XMLSAXParserProvider.java b/source/mir/util/xml/XMLSAXParserProvider.java index c5ee60ab..d47723c9 100755 --- a/source/mir/util/xml/XMLSAXParserProvider.java +++ b/source/mir/util/xml/XMLSAXParserProvider.java @@ -2,7 +2,7 @@ package mir.util.xml; import java.util.Map; -import mir.util.ExceptionFunctions; +import mir.util.ExceptionRoutines; import org.xml.sax.InputSource; import org.xml.sax.Locator; @@ -36,7 +36,7 @@ class XMLSAXParserProvider implements XMLParserEngine.XMLParserProvider { parser.parse(new InputSource(aReader), new SAXHandler(aReceiver)); } catch (org.xml.sax.SAXException e) { - Throwable t = ExceptionFunctions.traceCauseException(e); + Throwable t = ExceptionRoutines.traceCauseException(e); if (t instanceof XMLParserExc) { throw (XMLParserExc) t; diff --git a/source/mircoders/abuse/FilterEngine.java b/source/mircoders/abuse/FilterEngine.java index 41b0d40a..1981946a 100755 --- a/source/mircoders/abuse/FilterEngine.java +++ b/source/mircoders/abuse/FilterEngine.java @@ -360,7 +360,7 @@ public class FilterEngine { while (i.hasNext()) { EntityAdapter entityAdapter = (EntityAdapter) i.next(); List filters = new ArrayList(); - Iterator j = (Iterator) entityAdapter.get("to_filters"); + Iterator j = (Iterator) entityAdapter.getIterator("to_filters"); while (j.hasNext()) { filters.add(((EntityAdapter) j.next()).getEntity()); } diff --git a/source/mircoders/entity/EntityImages.java b/source/mircoders/entity/EntityImages.java index eb6392ae..0c8f28ef 100755 --- a/source/mircoders/entity/EntityImages.java +++ b/source/mircoders/entity/EntityImages.java @@ -30,18 +30,15 @@ package mircoders.entity; +import mir.log.LoggerWrapper; +import mir.media.image.ImageMagickImageProcessor; +import mir.media.image.ImageProcessor; +import mir.storage.DatabaseFailure; + import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.sql.SQLException; -import mir.log.LoggerWrapper; -import mir.storage.DatabaseFailure; -import mir.util.StreamCopier; -import mir.media.image.ImageProcessor; -// FIXME: delete this when finished testing ImageMagickImageProcessor -//import mir.media.image.JAIImageProcessor; -import mir.media.image.ImageMagickImageProcessor; - public class EntityImages extends EntityUploadedMedia { private int maxImageSize = configuration.getInt("Producer.Image.MaxSize"); @@ -75,13 +72,8 @@ public class EntityImages extends EntityUploadedMedia public void setImage(InputStream anInputStream, String type) throws DatabaseFailure { if (anInputStream != null) { try { - // FIXME: delete this when finished testing ImageMagickImageProcessor - //ByteArrayOutputStream inputData = new ByteArrayOutputStream(); - //StreamCopier.copy(anInputStream, inputData); - ImageProcessor processor = new ImageMagickImageProcessor(anInputStream); - // FIXME: delete this when finished testing ImageMagickImageProcessor - //ImageProcessor processor = new JAIImageProcessor(inputData.toByteArray()); + processor.descaleImage(maxImageSize, minDescaleRatio, minDescaleReduction); ByteArrayOutputStream imageData = new ByteArrayOutputStream(); diff --git a/source/mircoders/global/Abuse.java b/source/mircoders/global/Abuse.java index a6afb11d..e7dc56fd 100755 --- a/source/mircoders/global/Abuse.java +++ b/source/mircoders/global/Abuse.java @@ -51,7 +51,7 @@ import mir.entity.Entity; import mir.entity.adapter.EntityAdapterModel; import mir.log.LoggerWrapper; import mir.session.Request; -import mir.util.DateTimeFunctions; +import mir.util.DateTimeRoutines; import mir.util.EntityUtility; import mir.util.GeneratorFormatAdapters; import mir.util.StringRoutines; @@ -159,7 +159,7 @@ public class Abuse { StringBuffer line = new StringBuffer(); - line.append(DateTimeFunctions.advancedDateFormat( + line.append(DateTimeRoutines.advancedDateFormat( configuration.getString("Mir.DefaultDateTimeFormat"), (new GregorianCalendar()).getTime(), configuration.getString("Mir.DefaultTimezone"))); @@ -199,7 +199,7 @@ public class Abuse { StringBuffer line = new StringBuffer(); - line.append(DateTimeFunctions.advancedDateFormat( + line.append(DateTimeRoutines.advancedDateFormat( configuration.getString("Mir.DefaultDateTimeFormat"), (new GregorianCalendar()).getTime(), configuration.getString("Mir.DefaultTimezone"))); diff --git a/source/mircoders/global/ProducerEngine.java b/source/mircoders/global/ProducerEngine.java index 3de07eaa..201183aa 100755 --- a/source/mircoders/global/ProducerEngine.java +++ b/source/mircoders/global/ProducerEngine.java @@ -41,6 +41,7 @@ import mir.log.LoggerToWriterAdapter; import mir.log.LoggerWrapper; import mir.producer.Producer; import mir.producer.ProducerFactory; +import mir.producer.ProductionContext; import mir.util.GeneratorFormatAdapters; import mir.util.StringRoutines; @@ -195,6 +196,7 @@ public class ProducerEngine { private String factoryName; private String verb; private Producer producer; + private ProductionContext productionContext; public ProducerJob(String aFactory, String aVerb) { factoryName = aFactory; @@ -211,17 +213,17 @@ public class ProducerEngine { } public void abort() { - if (producer!=null) { - producer.abort(); + if (producer!=null && productionContext!=null) { + producer.abort(productionContext); } } public boolean run() { - ProducerFactory factory; + final ProducerFactory factory; long startTime; long endTime; boolean result = false; - Map startingMap = new HashMap(); + final Map startingMap = new HashMap(); Map mirMap = new HashMap(); mirMap.put("producer", factoryName); mirMap.put("verb", verb); @@ -240,8 +242,43 @@ public class ProducerEngine { synchronized(factory) { producer = factory.makeProducer(verb, startingMap); } + if (producer!=null) { - result = producer.produce(logger); + try { + MirGlobal.localizer().producers().beforeProducerTask(factoryName, verb); + } + catch (Throwable t) { + logger.warn("Misbehaving beforeProducerTask",t ); + } + + productionContext = new ProductionContext() { + public ProducerFactory getFactory() { + return factory; + } + + public Producer getProducer() { + return producer; + } + + public String getVerb() { + return verb; + } + + public LoggerWrapper getLogger() { + return logger; + } + + public Map getValueSet() { + return startingMap; + } + }; + result = producer.execute(productionContext); + try { + MirGlobal.localizer().producers().afterProducerTask(factoryName, verb); + } + catch (Throwable t) { + logger.warn("Misbehaving afterProducerTask", t); + } } } } diff --git a/source/mircoders/localizer/MirAdminInterfaceLocalizer.java b/source/mircoders/localizer/MirAdminInterfaceLocalizer.java index 35777234..3c5880dd 100755 --- a/source/mircoders/localizer/MirAdminInterfaceLocalizer.java +++ b/source/mircoders/localizer/MirAdminInterfaceLocalizer.java @@ -101,8 +101,19 @@ public interface MirAdminInterfaceLocalizer { public List simpleArticleOperations(); public interface MirSimpleEntityOperation { + /** + * Returns the name of the operation. Must be unique and immutable. + */ public String getName(); + + /** + * Is the operation valid for the given {@link EntityAdapter} + */ public boolean isAvailable(EntityAdapter anEntity) throws MirLocalizerExc, MirLocalizerFailure; + + /** + * perform the operation on the given {@link EntityAdapter} as the given user + */ public void perform(EntityAdapter aUser, EntityAdapter anEntity) throws MirLocalizerExc, MirLocalizerFailure; } } \ No newline at end of file diff --git a/source/mircoders/localizer/MirLocalizer.java b/source/mircoders/localizer/MirLocalizer.java index 31651946..228193a4 100755 --- a/source/mircoders/localizer/MirLocalizer.java +++ b/source/mircoders/localizer/MirLocalizer.java @@ -48,6 +48,7 @@ package mircoders.localizer; * classes can be extended to override default behavior.

* */ + public interface MirLocalizer { public MirProducerLocalizer producers() throws MirLocalizerFailure, MirLocalizerExc; public MirAdminInterfaceLocalizer adminInterface() throws MirLocalizerFailure, MirLocalizerExc; diff --git a/source/mircoders/localizer/MirProducerLocalizer.java b/source/mircoders/localizer/MirProducerLocalizer.java index 25e600d7..962ad5d9 100755 --- a/source/mircoders/localizer/MirProducerLocalizer.java +++ b/source/mircoders/localizer/MirProducerLocalizer.java @@ -40,4 +40,7 @@ public interface MirProducerLocalizer { public List getRecipeNames() throws MirLocalizerExc, MirLocalizerFailure; public void produceRecipe(String aName) throws MirLocalizerExc, MirLocalizerFailure; + + public void beforeProducerTask(String aFactory, String aVerb); + public void afterProducerTask(String aFactory, String aVerb); } diff --git a/source/mircoders/localizer/basic/MirBasicAdminInterfaceLocalizer.java b/source/mircoders/localizer/basic/MirBasicAdminInterfaceLocalizer.java index da30fb26..d90f62ee 100755 --- a/source/mircoders/localizer/basic/MirBasicAdminInterfaceLocalizer.java +++ b/source/mircoders/localizer/basic/MirBasicAdminInterfaceLocalizer.java @@ -52,7 +52,7 @@ import mir.log.LoggerWrapper; import mir.misc.StringUtil; import mir.module.ModuleExc; import mir.storage.DatabaseFailure; -import mir.util.DateTimeFunctions; +import mir.util.DateTimeRoutines; import mir.util.EntityUtility; import mir.util.StringRoutines; import mir.util.generator.BundleGeneratorFunction; @@ -247,7 +247,7 @@ public class MirBasicAdminInterfaceLocalizer implements MirAdminInterfaceLocaliz try { StringBuffer line = new StringBuffer(); - line.append(DateTimeFunctions.advancedDateFormat( + line.append(DateTimeRoutines.advancedDateFormat( MirGlobal.config().getString("Mir.DefaultDateTimeFormat"), (new GregorianCalendar()).getTime(), MirGlobal.config().getString("Mir.DefaultTimezone"))); diff --git a/source/mircoders/localizer/basic/MirBasicDataModelLocalizer.java b/source/mircoders/localizer/basic/MirBasicDataModelLocalizer.java index 54d914ed..e0153914 100755 --- a/source/mircoders/localizer/basic/MirBasicDataModelLocalizer.java +++ b/source/mircoders/localizer/basic/MirBasicDataModelLocalizer.java @@ -29,19 +29,9 @@ */ package mircoders.localizer.basic; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - import mir.config.MirPropertiesConfiguration; import mir.entity.Entity; -import mir.entity.adapter.EntityAdapter; -import mir.entity.adapter.EntityAdapterDefinition; -import mir.entity.adapter.EntityAdapterModel; -import mir.entity.adapter.ToManyRelationField; -import mir.entity.adapter.ToOneRelationField; +import mir.entity.adapter.*; import mir.generator.Generator; import mir.generator.GeneratorExc; import mir.generator.GeneratorFailure; @@ -50,7 +40,6 @@ import mir.media.MediaHandler; import mir.misc.NumberUtils; import mir.util.JDBCStringRoutines; import mir.util.ParameterExpander; -import mir.util.RewindableIterator; import mir.util.StructuredContentParser; import mircoders.entity.EntityUploadedMedia; import mircoders.global.MirGlobal; @@ -61,29 +50,11 @@ import mircoders.localizer.MirLocalizerFailure; import mircoders.media.MediaHelper; import mircoders.module.ModuleContent; import mircoders.module.ModuleLanguage; -import mircoders.storage.DatabaseArticleType; -import mircoders.storage.DatabaseAudio; -import mircoders.storage.DatabaseBreaking; -import mircoders.storage.DatabaseComment; -import mircoders.storage.DatabaseCommentStatus; -import mircoders.storage.DatabaseContent; -import mircoders.storage.DatabaseContentToMedia; -import mircoders.storage.DatabaseContentToTopics; -import mircoders.storage.DatabaseFilter; -import mircoders.storage.DatabaseFilterGroup; -import mircoders.storage.DatabaseImageType; -import mircoders.storage.DatabaseImages; -import mircoders.storage.DatabaseLanguage; -import mircoders.storage.DatabaseMediaType; -import mircoders.storage.DatabaseMediafolder; -import mircoders.storage.DatabaseMessages; -import mircoders.storage.DatabaseOther; -import mircoders.storage.DatabaseTopics; -import mircoders.storage.DatabaseUploadedMedia; -import mircoders.storage.DatabaseUsers; -import mircoders.storage.DatabaseVideo; +import mircoders.storage.*; import multex.Failure; +import java.util.*; + public class MirBasicDataModelLocalizer implements MirDataModelLocalizer { protected LoggerWrapper logger = new LoggerWrapper("Localizer.DataModel"); protected MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance(); @@ -623,15 +594,14 @@ public class MirBasicDataModelLocalizer implements MirDataModelLocalizer { public Object getValue(EntityAdapter anEntityAdapter) { EntityAdapter media; Entity mediaType; - RewindableIterator iterator; + Iterator iterator; Map result; MediaHandler mediaHandler; String tinyIcon; String iconAlt; try { - iterator = (RewindableIterator) (anEntityAdapter.get("to_uploaded_media")); - iterator.rewind(); + iterator = anEntityAdapter.getIterator("to_uploaded_media"); tinyIcon = MirGlobal.config().getString("Producer.Icon.TinyText"); iconAlt = "Text"; diff --git a/source/mircoders/localizer/basic/MirBasicGeneratorLocalizer.java b/source/mircoders/localizer/basic/MirBasicGeneratorLocalizer.java index db5dd616..cd9afe32 100755 --- a/source/mircoders/localizer/basic/MirBasicGeneratorLocalizer.java +++ b/source/mircoders/localizer/basic/MirBasicGeneratorLocalizer.java @@ -57,9 +57,11 @@ public class MirBasicGeneratorLocalizer implements MirGeneratorLocalizer { "freemarker", new FreemarkerGenerator.FreemarkerGeneratorLibraryFactory( MirGlobal.config().getHome())); + aRepository.registerLibraryFactory( "velocity", new VelocityGenerator.VelocityGeneratorLibraryFactory(MirGlobal.config().getHome() ) ); + aRepository.registerLibraryFactory( "tal", new TALGenerator.TALGeneratorLibraryFactory(MirGlobal.config().getHome() ) ); diff --git a/source/mircoders/localizer/basic/MirBasicLocalizer.java b/source/mircoders/localizer/basic/MirBasicLocalizer.java index a688c580..aeaa1b85 100755 --- a/source/mircoders/localizer/basic/MirBasicLocalizer.java +++ b/source/mircoders/localizer/basic/MirBasicLocalizer.java @@ -29,16 +29,9 @@ */ package mircoders.localizer.basic; -import mircoders.localizer.MirAdminInterfaceLocalizer; -import mircoders.localizer.MirDataModelLocalizer; -import mircoders.localizer.MirGeneratorLocalizer; -import mircoders.localizer.MirLocalizer; -import mircoders.localizer.MirLocalizerExc; -import mircoders.localizer.MirLocalizerFailure; -import mircoders.localizer.MirMediaLocalizer; -import mircoders.localizer.MirOpenPostingLocalizer; -import mircoders.localizer.MirProducerAssistantLocalizer; -import mircoders.localizer.MirProducerLocalizer; +import mircoders.localizer.*; + +import java.io.File; public class MirBasicLocalizer implements MirLocalizer { @@ -69,4 +62,4 @@ public class MirBasicLocalizer implements MirLocalizer { public MirMediaLocalizer media() throws MirLocalizerFailure, MirLocalizerExc { return new MirBasicMediaLocalizer(); } -} \ No newline at end of file +} diff --git a/source/mircoders/localizer/basic/MirBasicPostingSessionHandler.java b/source/mircoders/localizer/basic/MirBasicPostingSessionHandler.java index a7b8145d..31822f50 100755 --- a/source/mircoders/localizer/basic/MirBasicPostingSessionHandler.java +++ b/source/mircoders/localizer/basic/MirBasicPostingSessionHandler.java @@ -29,29 +29,19 @@ */ package mircoders.localizer.basic; -import java.io.File; -import java.io.FileInputStream; -import java.io.FilenameFilter; -import java.io.IOException; -import java.io.InputStream; -import java.util.*; - import mir.config.MirPropertiesConfiguration; import mir.log.LoggerWrapper; -import mir.session.Request; -import mir.session.Response; -import mir.session.Session; -import mir.session.SessionExc; -import mir.session.SessionFailure; -import mir.session.SessionHandler; -import mir.session.UploadedFile; -import mir.session.ValidationError; +import mir.session.*; import mir.storage.Database; -import mir.util.ExceptionFunctions; -import mir.util.FileFunctions; +import mir.util.ExceptionRoutines; +import mir.util.FileRoutines; +import mir.util.IORoutines; import mircoders.global.MirGlobal; import mircoders.media.UnsupportedMediaTypeExc; +import java.io.*; +import java.util.*; + /** * Extensible handler for open postings. * Behaviour can be altered by overriding methods. @@ -217,7 +207,7 @@ public abstract class MirBasicPostingSessionHandler implements SessionHandler { if (configuration.getBoolean("Localizer.OpenSession.AllowFTPUploads", false)) { aResponse.setResponseValue("ftpfiles", - FileFunctions.getDirectoryContentsAsList(configuration.getFile("Localizer.OpenSession.FTPDirectory"), + FileRoutines.getDirectoryContentsAsList(configuration.getFile("Localizer.OpenSession.FTPDirectory"), new FilenameFilter() { public boolean accept(File aDir, String aName) { return !(new File(aDir, aName).isDirectory()); @@ -329,7 +319,16 @@ public abstract class MirBasicPostingSessionHandler implements SessionHandler { preprocessNewAttachment(aRequest, aSession, new UploadedFile() { public void writeToFile(File aFile) throws SessionFailure { try { - FileFunctions.move(sourceFile, aFile); + FileRoutines.move(sourceFile, aFile); + } + catch (IOException e) { + throw new SessionFailure(e); + } + } + + public void writeToStream(OutputStream aStream) throws SessionFailure { + try { + IORoutines.copyStream(getInputStream(), aStream); } catch (IOException e) { throw new SessionFailure(e); @@ -378,7 +377,7 @@ public abstract class MirBasicPostingSessionHandler implements SessionHandler { } protected void makeErrorResponse(Request aRequest, Session aSession, Response aResponse, Throwable anError) throws SessionExc, SessionFailure { - Throwable rootCause = ExceptionFunctions.traceCauseException(anError); + Throwable rootCause = ExceptionRoutines.traceCauseException(anError); if (rootCause instanceof DuplicatePostingExc) aResponse.setResponseGenerator(dupeResponseGenerator); @@ -512,6 +511,15 @@ public abstract class MirBasicPostingSessionHandler implements SessionHandler { uploadedFile.writeToFile(aFile); } + public void writeToStream(OutputStream aStream) throws SessionExc, SessionFailure { + try { + IORoutines.copyStream(uploadedFile.getInputStream(), aStream); + } + catch (IOException e) { + throw new SessionFailure(e); + } + } + public InputStream getInputStream() throws SessionExc, SessionFailure { return uploadedFile.getInputStream(); } diff --git a/source/mircoders/localizer/basic/MirBasicProducerLocalizer.java b/source/mircoders/localizer/basic/MirBasicProducerLocalizer.java index 541d60b3..e04200fe 100755 --- a/source/mircoders/localizer/basic/MirBasicProducerLocalizer.java +++ b/source/mircoders/localizer/basic/MirBasicProducerLocalizer.java @@ -131,6 +131,12 @@ public class MirBasicProducerLocalizer implements MirProducerLocalizer { throw new MirLocalizerExc("Unknown recipe name: " + aName); } + public void beforeProducerTask(String aFactory, String aVerb) { + } + + public void afterProducerTask(String aFactory, String aVerb) { + } + /** * Loads factories from a file with a {@link ProducerConfigReader} */ diff --git a/source/mircoders/localizer/basic/MirBasicWriterEngine.java b/source/mircoders/localizer/basic/MirBasicWriterEngine.java index c277abf0..693e19b1 100755 --- a/source/mircoders/localizer/basic/MirBasicWriterEngine.java +++ b/source/mircoders/localizer/basic/MirBasicWriterEngine.java @@ -29,18 +29,19 @@ */ package mircoders.localizer.basic; -import java.io.*; - +import mir.config.MirPropertiesConfiguration; import mir.generator.WriterEngine; import mir.log.LoggerWrapper; -import mir.config.MirPropertiesConfiguration; -import mir.util.FileFunctions; +import mir.util.FileRoutines; +import mircoders.global.MirGlobal; import mircoders.localizer.MirLocalizerFailure; +import java.io.*; + public class MirBasicWriterEngine implements WriterEngine { private String defaultEncoding; - protected static LoggerWrapper logger = new LoggerWrapper("Localizer.AdminInterface"); + protected static LoggerWrapper logger = new LoggerWrapper("Localizer.WriterEngine"); protected MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance(); /** @@ -57,9 +58,9 @@ public class MirBasicWriterEngine implements WriterEngine { * {@inheritDoc} */ public Object openWriter(String anIdentifier, String anEncoding) throws MirLocalizerFailure { + System.out.println("Opening writer for " + anIdentifier); + String encoding; - File file; - File dir; if (anEncoding != null && !anEncoding.equals("")) { encoding = anEncoding; @@ -68,17 +69,17 @@ public class MirBasicWriterEngine implements WriterEngine { encoding = defaultEncoding; } - try { - file = new File(anIdentifier); + File destinationFile = new File(anIdentifier); - dir = file.getParentFile(); + File destinationDirectory = destinationFile.getParentFile(); - if (dir != null && !dir.exists()) { - dir.mkdirs(); - } + if (destinationDirectory != null && !destinationDirectory.exists()) { + destinationDirectory.mkdirs(); + } + try { return new PrintWriter( - new TempWriter(file, encoding) + new TempWriter(destinationFile, encoding) ); } catch (IOException t) { @@ -94,6 +95,7 @@ public class MirBasicWriterEngine implements WriterEngine { TempWriter(File aDestination, String anEncoding) throws IOException { destinationFile = aDestination; slaveFile = File.createTempFile("Mir", ".generated", tempDirectory); + slaveFile.deleteOnExit(); slaveWriter = new BufferedWriter( new OutputStreamWriter( new FileOutputStream(slaveFile), anEncoding @@ -102,7 +104,17 @@ public class MirBasicWriterEngine implements WriterEngine { public void close() throws IOException { slaveWriter.close(); - FileFunctions.move(slaveFile, destinationFile); + + try { + FileRoutines.move(slaveFile, destinationFile); + + slaveFile.delete(); + } + catch (Throwable e) { + System.out.println("error: " + e.toString()); + + throw new IOException(e.getMessage()); + } } public void flush() throws IOException { diff --git a/source/mircoders/localizer/basic/actions/ArticleTopicAction.java b/source/mircoders/localizer/basic/actions/ArticleTopicAction.java index 36750166..38f876a8 100755 --- a/source/mircoders/localizer/basic/actions/ArticleTopicAction.java +++ b/source/mircoders/localizer/basic/actions/ArticleTopicAction.java @@ -74,6 +74,7 @@ public class ArticleTopicAction implements MirBasicAdminInterfaceLocalizer.MirSi db.setTopics(anEntity.getEntity().getId(), topicsToSet); } + public void perform2(EntityAdapter aUser, EntityAdapter anEntity) throws MirLocalizerExc, MirLocalizerFailure { DatabaseContentToTopics db = DatabaseContentToTopics.getInstance(); diff --git a/source/mircoders/media/AbstractMediaHandler.java b/source/mircoders/media/AbstractMediaHandler.java index 94cbb9bd..501a865e 100755 --- a/source/mircoders/media/AbstractMediaHandler.java +++ b/source/mircoders/media/AbstractMediaHandler.java @@ -29,20 +29,34 @@ */ package mircoders.media; -import java.io.File; - import mir.entity.Entity; import mir.media.MediaExc; import mir.media.MediaFailure; import mir.media.MediaHandler; import mir.misc.StringUtil; +import java.io.*; + public abstract class AbstractMediaHandler implements MediaHandler { - public File getStorageFile(Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure { - return new File(new File(getStoragePath()), getRelativeStorageFile(aMedia, aMediaType)); + protected InputStream getStorageInputStream(Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure { + try { + return new FileInputStream(getMediaStorageFile(aMedia, aMediaType)); + } + catch (Throwable e) { + throw new MediaFailure(e); + } + } + + protected OutputStream getStorageOutputStream(Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure { + try { + return new FileOutputStream(getMediaStoragePath(aMedia, aMediaType)); + } + catch (Throwable e) { + throw new MediaFailure(e); + } } - public String getRelativeStorageFile(Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure { + protected String getRelativeMediaStoragePath(Entity aMedia, Entity aMediaType) { String publishPath = aMedia.getFieldValue("publish_path"); if (publishPath==null || publishPath.length()==0) { @@ -50,9 +64,19 @@ public abstract class AbstractMediaHandler implements MediaHandler { String mediaFileName = aMedia.getId() + "." + extension; String date = aMedia.getFieldValue("date"); String datePath = StringUtil.webdbDate2path(date); - return (new File(datePath, mediaFileName)).getPath(); + + return datePath + "/" + mediaFileName; } + return publishPath; } + protected String getMediaStoragePath(Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure { + return getBaseStoragePath() + "/" + getRelativeMediaStoragePath(aMedia, aMediaType); + } + + protected final File getMediaStorageFile(Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure { + return new File(getMediaStoragePath(aMedia, aMediaType)); + } + } diff --git a/source/mircoders/media/MediaHandlerGeneric.java b/source/mircoders/media/MediaHandlerGeneric.java index e8e66ca4..f50936d7 100755 --- a/source/mircoders/media/MediaHandlerGeneric.java +++ b/source/mircoders/media/MediaHandlerGeneric.java @@ -29,13 +29,6 @@ */ package mircoders.media; -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; - -import javax.servlet.ServletContext; - import mir.config.MirPropertiesConfiguration; import mir.entity.Entity; import mir.log.LoggerWrapper; @@ -43,7 +36,12 @@ import mir.media.MediaExc; import mir.media.MediaFailure; import mir.misc.StringUtil; import mir.session.UploadedFile; -import mir.util.FileFunctions; +import mir.util.IORoutines; + +import javax.servlet.ServletContext; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStream; /** @@ -63,37 +61,20 @@ import mir.util.FileFunctions; * * @see mir.media.MediaHandler * @author mh - * @version $Id: MediaHandlerGeneric.java,v 1.20.2.8 2005/02/10 16:22:23 rhindes Exp $ + * @version $Id: MediaHandlerGeneric.java,v 1.20.2.9 2005/08/21 17:09:23 zapata Exp $ */ -public class MediaHandlerGeneric extends AbstractMediaHandler -{ +public class MediaHandlerGeneric extends AbstractMediaHandler { protected static MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance(); protected LoggerWrapper logger = new LoggerWrapper("Media.Generic"); /** {@inheritDoc} */ - public void store(File aFile, Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure { - try { - FileFunctions.move(aFile, getStorageFile(aMedia, aMediaType)); - - aMedia.setFieldValue("publish_path", getRelativeStorageFile(aMedia, aMediaType)); - aMedia.setFieldValue("size", Long.toString(getStorageFile(aMedia, aMediaType).length())); - aMedia.update(); - } - catch (Throwable e) { - logger.error("MediaHandlerGeneric.set: " + e.toString()); - throw new MediaFailure(e); - } - } - - /** {@inheritDoc} */ public void store(UploadedFile anUploadedFile, Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure { try { - anUploadedFile.writeToFile(getStorageFile(aMedia, aMediaType)); - - aMedia.setFieldValue("publish_path", getRelativeStorageFile(aMedia, aMediaType)); - aMedia.setFieldValue("size", Long.toString(getStorageFile(aMedia, aMediaType).length())); + anUploadedFile.writeToFile(getMediaStorageFile(aMedia, aMediaType)); + aMedia.setFieldValue("publish_path", getRelativeMediaStoragePath(aMedia, aMediaType)); + aMedia.setFieldValue("size", Long.toString(getMediaStorageFile(aMedia, aMediaType).length())); aMedia.update(); } catch (Throwable e) { @@ -105,10 +86,10 @@ public class MediaHandlerGeneric extends AbstractMediaHandler /** {@inheritDoc} */ public void store(InputStream anInputStream, Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure { try { - FileFunctions.copy(anInputStream, getStorageFile(aMedia, aMediaType)); + IORoutines.copyStream(anInputStream, new FileOutputStream(getMediaStorageFile(aMedia, aMediaType))); - aMedia.setFieldValue("publish_path", getRelativeStorageFile(aMedia, aMediaType)); - aMedia.setFieldValue("size", Long.toString(getStorageFile(aMedia, aMediaType).length())); + aMedia.setFieldValue("publish_path", getRelativeMediaStoragePath(aMedia, aMediaType)); + aMedia.setFieldValue("size", Long.toString(getMediaStorageFile(aMedia, aMediaType).length())); aMedia.update(); } catch (Throwable e) { @@ -117,21 +98,17 @@ public class MediaHandlerGeneric extends AbstractMediaHandler } } + /** {@inheritDoc} */ public void produce(Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure { - if (!getStorageFile(aMedia, aMediaType).exists()) - throw new MediaExc("error in producing media:: " + getStorageFile(aMedia, aMediaType) + " does not exist!"); + if (!getMediaStorageFile(aMedia, aMediaType).exists()) { + throw new MediaExc("error in producing media:: " + getMediaStorageFile(aMedia, aMediaType) + " does not exist!"); + } } - /** - * Get access to the raw media data by an {@link InputStream} - */ + /** {@inheritDoc} */ public InputStream getMedia(Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure { - File file = getStorageFile(aMedia, aMediaType); - if (!file.exists()) - throw new MediaExc("error in MirMediaHandler.getMedia(): " + file + " does not exist!"); - try { - return new BufferedInputStream(new FileInputStream(file)); + return new FileInputStream(getMediaStorageFile(aMedia, aMediaType)); } catch (Throwable e) { throw new MediaFailure("MediaHandlerGeneric.getMedia(): " + e.toString(), e); @@ -149,11 +126,11 @@ public class MediaHandlerGeneric extends AbstractMediaHandler return servletContext.getMimeType(fileName); } - public String getStoragePath() { + public String getBaseStoragePath() { return configuration.getString("Producer.Media.Path"); } - public String getIconStoragePath() { + public String getBaseIconStoragePath() { return configuration.getString("Producer.Image.IconPath"); } diff --git a/source/mircoders/media/MediaHandlerImages.java b/source/mircoders/media/MediaHandlerImages.java index d4087e3e..41bb4355 100755 --- a/source/mircoders/media/MediaHandlerImages.java +++ b/source/mircoders/media/MediaHandlerImages.java @@ -29,20 +29,21 @@ */ package mircoders.media; -import java.io.*; - import mir.config.MirPropertiesConfiguration; import mir.entity.Entity; import mir.log.LoggerWrapper; import mir.media.MediaExc; import mir.media.MediaFailure; import mir.media.MediaHandler; -import mir.misc.FileUtil; import mir.misc.StringUtil; import mir.session.SessionExc; import mir.session.UploadedFile; +import mir.util.IORoutines; +import mir.util.FileRoutines; import mircoders.entity.EntityImages; +import java.io.*; + /** * This class handles saving, fetching creating representations * for all images. The image content is stored in the DB. The content is @@ -57,7 +58,7 @@ import mircoders.entity.EntityImages; * * @see mir.media.MediaHandler * @author mh - * @version $Id: MediaHandlerImages.java,v 1.23.2.8 2005/03/26 11:26:26 zapata Exp $ + * @version $Id: MediaHandlerImages.java,v 1.23.2.9 2005/08/21 17:09:23 zapata Exp $ */ @@ -105,47 +106,72 @@ public abstract class MediaHandlerImages extends AbstractMediaHandler implements } } - public void store(File aFile, Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure { - try { - store(new FileInputStream(aFile), aMedia, aMediaType); - } - catch (FileNotFoundException e) { - throw new MediaFailure(e); - } - } - public void produce(Entity ent, Entity mediaTypeEnt) throws MediaExc, MediaFailure { String date = ent.getFieldValue("date"); String datePath = StringUtil.webdbDate2path(date); String ext = "."+mediaTypeEnt.getFieldValue("name"); String filepath = datePath+ent.getId()+ext; - String iconFilePath = configuration.getString("Producer.StorageRoot") - +getIconStoragePath() + filepath; - String productionFilePath = getStoragePath() + File.separator + filepath; + String iconFilePath = configuration.getString("Producer.StorageRoot") + getBaseIconStoragePath() + filepath; + String productionFilePath = getBaseStoragePath() + File.separator + filepath; if (ent.getFieldValue("icon_data")!= null && ent.getFieldValue("image_data")!= null) { // make icon try { + OutputStream out; InputStream in = new ByteArrayInputStream(((EntityImages) ent).getIcon()); - FileUtil.write(iconFilePath, in); + try { + File iconFile = new File(iconFilePath); + + FileRoutines.createParentDirectories(iconFile); + + out = new FileOutputStream(iconFile); + try { + IORoutines.copyStream(in, out); + } + finally { + out.close(); + } + } + finally { + in.close(); + } in = new ByteArrayInputStream(((EntityImages) ent).getImage()); - FileUtil.write(productionFilePath, in); - ent.setFieldValue("icon_path",getIconStoragePath()+filepath); - ent.setFieldValue("publish_path",filepath); + try { + File imageFile = new File(productionFilePath); + + FileRoutines.createParentDirectories(imageFile); + + out = new FileOutputStream(imageFile); + try { + IORoutines.copyStream(in, out); + } + finally { + out.close(); + } + } + finally { + in.close(); + } + + ent.setFieldValue("icon_path", getBaseIconStoragePath() + filepath); + ent.setFieldValue("publish_path", filepath); ent.update(); } catch (Throwable e) { - logger.error("MediaHandlerImages.produce: " + e.toString()); - throw new MediaFailure("MediaHandlerImages.produce: " + e.toString(), e); + logger.error("Error producing image", e); + + throw new MediaFailure("Error producing image", e); + } + finally { } } else { - logger.error("MediaHandlerImages.produce: missing image or icon OID for: " + ent.getId()); + logger.error("Can't produce image " + ent.getId() + ": missing image or icon OID"); - throw new MediaExc("MediaHandlerImages.produce: missing image or icon OID for: " + ent.getId()); + throw new MediaExc("Can't produce image " + ent.getId() + ": missing image or icon OID"); } } @@ -159,11 +185,11 @@ public abstract class MediaHandlerImages extends AbstractMediaHandler implements } } - public String getStoragePath() { + public String getBaseStoragePath() { return configuration.getString("Producer.Image.Path"); } - public String getIconStoragePath() { + public String getBaseIconStoragePath() { return configuration.getString("Producer.Image.IconPath"); } diff --git a/source/mircoders/media/MediaHandlerImagesExtern.java b/source/mircoders/media/MediaHandlerImagesExtern.java index d12f111b..ac964787 100755 --- a/source/mircoders/media/MediaHandlerImagesExtern.java +++ b/source/mircoders/media/MediaHandlerImagesExtern.java @@ -40,15 +40,12 @@ import mir.log.LoggerWrapper; import mir.media.MediaExc; import mir.media.MediaFailure; import mir.media.image.ImageProcessor; -// FIXME: delete this when finished testing ImageMagickImageProcessor -//import mir.media.image.JAIImageProcessor; import mir.media.image.ImageMagickImageProcessor; import mir.misc.StringUtil; - /** - * Image handler that stores images outside of the database. Will be replaced by the new - * media handling system. + * Image handler that stores images outside of the database. + * * @author Zapata * @version 1.0 */ @@ -75,19 +72,17 @@ public class MediaHandlerImagesExtern extends MediaHandlerGeneric String ext = "." + mediaTypeEnt.getFieldValue("name"); String fileBasePath = datePath + anImageEntity.getId(); String filePath = fileBasePath + ext; - String iconPath = getIconStoragePath() + fileBasePath + ".jpg"; + String iconPath = getBaseIconStoragePath() + fileBasePath + ".jpg"; String iconStoragePath = configuration.getString("Producer.StorageRoot") + iconPath; - String imageFilePath = getStoragePath() + File.separator + filePath; + String imageFilePath = getBaseStoragePath() + File.separator + filePath; File imageFile = new File(imageFilePath); File iconFile = new File(iconStoragePath); if (!imageFile.exists()) { - throw new MediaExc("error in MediaHandlerImagesExtern.produce(): " + filePath + " does not exist!"); + throw new MediaExc("error in MediaHandlerImagesExtern.execute(): " + filePath + " does not exist!"); } else { - // FIXME: delete this when finished testing ImageMagickImageProcessor - // ImageProcessor processor = new JAIImageProcessor(imageFile); ImageProcessor processor = new ImageMagickImageProcessor(imageFile); processor.descaleImage(maxIconSize, minDescaleRatio, minDescaleReduction); @@ -113,7 +108,7 @@ public class MediaHandlerImagesExtern extends MediaHandlerGeneric } } catch(Throwable t) { - logger.error("MediaHandlerImagesExtern.produce: " + t.toString()); + logger.error("MediaHandlerImagesExtern.execute: " + t.toString()); t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); throw new MediaFailure(t.getMessage(), t); } @@ -142,12 +137,12 @@ public class MediaHandlerImagesExtern extends MediaHandlerGeneric return "image/jpeg"; } - public String getStoragePath() + public String getBaseStoragePath() { return configuration.getString("Producer.Image.Path"); } - public String getIconStoragePath() + public String getBaseIconStoragePath() { return configuration.getString("Producer.Image.IconPath"); } diff --git a/source/mircoders/media/MediaHandlerMp3.java b/source/mircoders/media/MediaHandlerMp3.java index 9b4cd048..e01f79de 100755 --- a/source/mircoders/media/MediaHandlerMp3.java +++ b/source/mircoders/media/MediaHandlerMp3.java @@ -29,15 +29,16 @@ */ package mircoders.media; -import java.io.StringReader; - import mir.entity.Entity; import mir.log.LoggerWrapper; import mir.media.MediaExc; import mir.media.MediaFailure; import mir.media.MediaHandler; -import mir.misc.FileUtil; import mir.misc.StringUtil; +import mir.util.IORoutines; + +import java.io.File; +import java.io.FileOutputStream; /** * Please note: this media handler produces @@ -63,19 +64,18 @@ import mir.misc.StringUtil; * * @see mir.media.MediaHandler * @author mh - * @version $Id: MediaHandlerMp3.java,v 1.15.2.6 2005/02/10 16:22:23 rhindes Exp $ + * @version $Id: MediaHandlerMp3.java,v 1.15.2.7 2005/08/21 17:09:23 zapata Exp $ */ -public class MediaHandlerMp3 extends MediaHandlerAudio implements MediaHandler -{ - +public class MediaHandlerMp3 extends MediaHandlerAudio implements MediaHandler { public MediaHandlerMp3() { logger = new LoggerWrapper("Media.Audio.Mp3"); } + /** + * {@inheritDoc} + */ public void produce(Entity ent, Entity mediaTypeEnt) throws MediaExc, MediaFailure { - - // first check if the file exists super.produce(ent, mediaTypeEnt); String baseName = ent.getId(); @@ -86,16 +86,14 @@ public class MediaHandlerMp3 extends MediaHandlerAudio implements MediaHandler String playlistFile = baseName + ".pls"; try { - //write the "meta" files - //first the .m3u since it only contains one line - FileUtil.write(getStoragePath() + "/" + datePath + "/" + mpegURLFile, - new StringReader(mp3Pointer), "US-ASCII"); - //now the .pls file - FileUtil.write(getStoragePath() + "/" + datePath + "/" + playlistFile, - new StringReader(mp3Pointer), "US-ASCII"); + IORoutines.writeStream(mp3Pointer, "us-ascii", + new FileOutputStream(new File(getBaseStoragePath() + "/" + datePath + "/" + mpegURLFile))); + + IORoutines.writeStream(mp3Pointer, "us-ascii", + new FileOutputStream(new File(getBaseStoragePath() + "/" + datePath + "/" + playlistFile))); } catch (Throwable e) { - logger.error("MediaHandlerMp3.produce: " + e.toString()); + logger.error("MediaHandlerMp3.execute: " + e.toString()); throw new MediaFailure(e); } diff --git a/source/mircoders/media/MediaHandlerOgg.java b/source/mircoders/media/MediaHandlerOgg.java index 07935a35..1bb3bcfb 100755 --- a/source/mircoders/media/MediaHandlerOgg.java +++ b/source/mircoders/media/MediaHandlerOgg.java @@ -29,15 +29,16 @@ */ package mircoders.media; -import java.io.StringReader; - import mir.entity.Entity; import mir.log.LoggerWrapper; import mir.media.MediaExc; import mir.media.MediaFailure; import mir.media.MediaHandler; -import mir.misc.FileUtil; import mir.misc.StringUtil; +import mir.util.IORoutines; + +import java.io.File; +import java.io.FileOutputStream; /** * Please note: this media handler produces @@ -81,21 +82,14 @@ public class MediaHandlerOgg extends MediaHandlerAudio implements MediaHandler String date = ent.getFieldValue("date"); String datePath = StringUtil.webdbDate2path(date); String oggPointer = getPublishHost() + ent.getFieldValue("publish_path"); - //String mpegURLFile = baseName + ".m3u"; String playlistFile = baseName + ".pls"; try { - //write the "meta" files - //first the .m3u since it only contains one line - //dont write the .m3u it is an ogg vorbis file - //FileUtil.write(getStoragePath() + "/" + datePath + "/" + mpegURLFile, - //new StringReader(mp3Pointer), "US-ASCII"); - //now the .pls file - FileUtil.write(getStoragePath() + "/" + datePath + "/" + playlistFile, - new StringReader(oggPointer), "US-ASCII"); + IORoutines.writeStream(oggPointer, "us-ascii", + new FileOutputStream(getBaseStoragePath() + File.separator + datePath + File.separator + playlistFile)); } catch (Throwable e) { - logger.error("MediaHandlerOgg.produce: " + e.toString()); + logger.error("MediaHandlerOgg.execute: " + e.toString()); throw new MediaFailure(e); } diff --git a/source/mircoders/media/MediaHandlerRealAudio.java b/source/mircoders/media/MediaHandlerRealAudio.java index 608ead82..27d924a3 100755 --- a/source/mircoders/media/MediaHandlerRealAudio.java +++ b/source/mircoders/media/MediaHandlerRealAudio.java @@ -29,27 +29,25 @@ */ package mircoders.media; -import java.io.StringReader; - import mir.entity.Entity; import mir.log.LoggerWrapper; import mir.media.MediaExc; import mir.media.MediaFailure; import mir.media.MediaHandler; -import mir.misc.FileUtil; import mir.misc.StringUtil; +import mir.util.IORoutines; +import mircoders.global.MirGlobal; + +import java.io.FileOutputStream; +import java.io.File; /** * Handles realAudio .it manages the ram file. * - * 03.2002 - reworked Realmedia handling. -mh - * - * @see mir.media.MediaHandlerGeneric - * @see mir.media.MediaHandler * @author john , mh - * @version $Id: MediaHandlerRealAudio.java,v 1.19.2.7 2005/02/10 16:22:23 rhindes Exp $ + * @version $Id: MediaHandlerRealAudio.java,v 1.19.2.8 2005/08/21 17:09:23 zapata Exp $ */ @@ -71,17 +69,19 @@ public class MediaHandlerRealAudio extends MediaHandlerAudio implements MediaHan String RealMediaPointer = rtspMediaHost+ent.getFieldValue("publish_path"); String RealMediaFile = datePath+ent.getId()+".ram"; try { - //write an rm (ram?. -mh) file - FileUtil.write(super.getStoragePath()+"/"+RealMediaFile, - new StringReader(RealMediaPointer), "US-ASCII"); + //write a ram file + + IORoutines.writeStream(RealMediaPointer, "us-ascii", + new FileOutputStream(getBaseStoragePath() + File.separator + datePath + File.separator + RealMediaFile)); } catch (Throwable e) { - logger.error("MediaHandlerRealAudio.produce: " + e.toString()); + logger.error("Error while producing realmedia: " + e.toString(), e); + throw new MediaFailure(e); } } - public String getStoragePath() + public String getBaseStoragePath() { return configuration.getString("Producer.RealMedia.Path"); } diff --git a/source/mircoders/media/MediaHandlerRealVideo.java b/source/mircoders/media/MediaHandlerRealVideo.java index 26fe197e..ea1480bc 100755 --- a/source/mircoders/media/MediaHandlerRealVideo.java +++ b/source/mircoders/media/MediaHandlerRealVideo.java @@ -29,18 +29,16 @@ */ package mircoders.media; -import java.io.File; -import java.io.StringReader; - import mir.entity.Entity; import mir.log.LoggerWrapper; import mir.media.MediaExc; import mir.media.MediaFailure; import mir.media.MediaHandler; -import mir.misc.FileUtil; import mir.misc.StringUtil; +import mir.util.IORoutines; - +import java.io.File; +import java.io.FileOutputStream; /** * Handles realVideo .it manages the ram file. @@ -49,13 +47,11 @@ import mir.misc.StringUtil; * * @see mir.media.MediaHandler * @author john , mh - * @version $Id: MediaHandlerRealVideo.java,v 1.19.2.6 2005/02/10 16:22:23 rhindes Exp $ + * @version $Id: MediaHandlerRealVideo.java,v 1.19.2.7 2005/08/21 17:09:23 zapata Exp $ */ -public class MediaHandlerRealVideo extends MediaHandlerVideo implements MediaHandler -{ - +public class MediaHandlerRealVideo extends MediaHandlerVideo implements MediaHandler { public MediaHandlerRealVideo() { logger = new LoggerWrapper("Media.Video.Real"); } @@ -70,19 +66,20 @@ public class MediaHandlerRealVideo extends MediaHandlerVideo implements MediaHan String RealMediaPointer = rtspMediaHost+ent.getFieldValue("publish_path"); String RealMediaFile = datePath+ent.getId()+".ram"; + try { - //write an rm (ram?. -mh) file - FileUtil.write(super.getStoragePath()+File.separator+RealMediaFile, - new StringReader(RealMediaPointer), "US-ASCII"); + // write a ram file + IORoutines.writeStream(RealMediaPointer, "us-ascii", + new FileOutputStream(new File(super.getBaseStoragePath() + File.separator + RealMediaFile))); } catch (Throwable e) { - logger.error("MediaHandlerRealVideo.produce: " + e.toString()); + logger.error("MediaHandlerRealVideo.execute: " + e.toString()); throw new MediaFailure(e); } } - public String getStoragePath() { + public String getBaseStoragePath() { return configuration.getString("Producer.RealMedia.Path"); } diff --git a/source/mircoders/media/MediaHandlerVideo.java b/source/mircoders/media/MediaHandlerVideo.java index 4ba84d3d..61958707 100755 --- a/source/mircoders/media/MediaHandlerVideo.java +++ b/source/mircoders/media/MediaHandlerVideo.java @@ -37,10 +37,9 @@ import mir.media.MediaHandler; * It is like MediaHandlerAudio with different icons. * It is MediaHandlerGeneric with different icons. * - * @see mir.media.MediaHandlerGeneric * @see mir.media.MediaHandler * @author john - * @version $Id: MediaHandlerVideo.java,v 1.9.2.2 2004/11/21 22:07:14 zapata Exp $ + * @version $Id: MediaHandlerVideo.java,v 1.9.2.3 2005/08/21 17:09:23 zapata Exp $ */ public class MediaHandlerVideo extends MediaHandlerGeneric implements MediaHandler diff --git a/source/mircoders/media/MediaUploadProcessor.java b/source/mircoders/media/MediaUploadProcessor.java index b3f8b349..b014f58a 100755 --- a/source/mircoders/media/MediaUploadProcessor.java +++ b/source/mircoders/media/MediaUploadProcessor.java @@ -40,7 +40,7 @@ import mir.media.MediaHandler; import mir.misc.StringUtil; import mir.session.UploadedFile; import mir.storage.Database; -import mir.util.FileFunctions; +import mir.util.FileRoutines; import mircoders.module.ModuleMediaType; public class MediaUploadProcessor { @@ -66,7 +66,7 @@ public class MediaUploadProcessor { } if (mediaType==null) { - String extension = FileFunctions.getExtension(aFile.getFileName()); + String extension = FileRoutines.getExtension(aFile.getFileName()); mediaType = mediaTypeModule.findMediaTypeForExtension(extension); } diff --git a/source/mircoders/media/URLMediaHandler.java b/source/mircoders/media/URLMediaHandler.java index 68d54f61..c5604c7d 100755 --- a/source/mircoders/media/URLMediaHandler.java +++ b/source/mircoders/media/URLMediaHandler.java @@ -51,16 +51,6 @@ public class URLMediaHandler implements MediaHandler { /** * {@inheritDoc} - * - * Since this media handler assumes the media is stored on a wholly different - * server, this operation is not applicable - */ - public void store(File aFile, Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure { - throw new UnsupportedOperationException(); - } - - /** - * {@inheritDoc} */ public void produce(Entity anEntity, Entity aMediaTypeEntity) throws MediaExc, MediaFailure { // nothing to do here @@ -78,11 +68,11 @@ public class URLMediaHandler implements MediaHandler { return "application/octetstream"; } - public String getStoragePath () throws MediaExc, MediaFailure { + public String getBaseStoragePath () throws MediaExc, MediaFailure { throw new UnsupportedOperationException(); } - public String getIconStoragePath () throws MediaExc, MediaFailure { + public String getBaseIconStoragePath () throws MediaExc, MediaFailure { throw new UnsupportedOperationException(); } diff --git a/source/mircoders/module/ModuleMediaType.java b/source/mircoders/module/ModuleMediaType.java index 95e86c43..57887a82 100755 --- a/source/mircoders/module/ModuleMediaType.java +++ b/source/mircoders/module/ModuleMediaType.java @@ -78,7 +78,8 @@ public class ModuleMediaType extends AbstractModule { EntityList mediaTypes; try { - mediaTypes = DatabaseMediaType.getInstance().selectByWhereClause("name = '"+JDBCStringRoutines.escapeStringLiteral(anExtension)+"'"); + mediaTypes = DatabaseMediaType.getInstance().selectByWhereClause( + "name = '"+JDBCStringRoutines.escapeStringLiteral(anExtension.toLowerCase())+"'"); } catch (DatabaseExc e) { return null; diff --git a/source/mircoders/pdf/PDFGenerator.java b/source/mircoders/pdf/PDFGenerator.java index e1a2fa89..ebfe9844 100755 --- a/source/mircoders/pdf/PDFGenerator.java +++ b/source/mircoders/pdf/PDFGenerator.java @@ -45,7 +45,8 @@ import mir.config.MirPropertiesConfiguration; import mir.entity.EntityBrowser; import mir.log.LoggerWrapper; import mir.misc.StringUtil; -import mir.util.DateTimeFunctions; +import mir.util.DateTimeRoutines; +import mir.util.HTMLRoutines; import mircoders.entity.EntityContent; import mircoders.entity.EntityImages; import mircoders.storage.DatabaseImages; @@ -643,7 +644,7 @@ public class PDFGenerator{ String isHTML = entityContent.getFieldValue("is_html"); String theTitle = entityContent.getFieldValue("title"); String theCreator = entityContent.getFieldValue("creator"); - String theDate = DateTimeFunctions.advancedDateFormat( + String theDate = DateTimeRoutines.advancedDateFormat( configuration.getString("RDF.Meta.DateFormat"), StringUtil.convertMirInternalDateToDate(entityContent.getFieldValue("webdb_create")), configuration.getString("Mir.DefaultTimezone")); @@ -725,8 +726,8 @@ public class PDFGenerator{ theContent= noTags.substituteAll(theContent," "); theDescription= noTags.substituteAll(theDescription," "); - theContent=mir.util.Translate.decode(theContent); - theDescription=mir.util.Translate.decode(theDescription); + theContent = HTMLRoutines.resolveHTMLEntites(theContent); + theDescription = HTMLRoutines.resolveHTMLEntites(theDescription); RE re1 = new RE("\r?\n\r?\n"); String theDescription1 = re1.substituteAll(theDescription,"BREAKHERE"); diff --git a/source/mircoders/producer/ContentMarkingProducerNode.java b/source/mircoders/producer/ContentMarkingProducerNode.java index 94a2a2b1..4a78c411 100755 --- a/source/mircoders/producer/ContentMarkingProducerNode.java +++ b/source/mircoders/producer/ContentMarkingProducerNode.java @@ -29,18 +29,18 @@ */ package mircoders.producer; -import java.util.Map; - import mir.entity.Entity; import mir.entity.adapter.EntityAdapter; import mir.log.LoggerWrapper; +import mir.producer.AbstractProducerNode; import mir.producer.ProducerFailure; -import mir.producer.ProducerNode; import mir.util.ParameterExpander; import mircoders.entity.EntityContent; +import java.util.Map; + -public class ContentMarkingProducerNode implements ProducerNode { +public class ContentMarkingProducerNode extends AbstractProducerNode { private String contentKey; public ContentMarkingProducerNode(String aContentKey) { diff --git a/source/mircoders/producer/ContentModifyingProducerNode.java b/source/mircoders/producer/ContentModifyingProducerNode.java index 3aa63d11..6fd50449 100755 --- a/source/mircoders/producer/ContentModifyingProducerNode.java +++ b/source/mircoders/producer/ContentModifyingProducerNode.java @@ -29,17 +29,17 @@ */ package mircoders.producer; -import java.util.Map; - import mir.entity.Entity; import mir.entity.adapter.EntityAdapter; import mir.log.LoggerWrapper; +import mir.producer.AbstractProducerNode; import mir.producer.ProducerFailure; -import mir.producer.ProducerNode; import mir.util.ParameterExpander; import mircoders.entity.EntityContent; -public class ContentModifyingProducerNode implements ProducerNode { +import java.util.Map; + +public class ContentModifyingProducerNode extends AbstractProducerNode { private String contentKey; private String fieldNameExpression; private String valueExpression; diff --git a/source/mircoders/producer/IndexingProducerNode.java b/source/mircoders/producer/IndexingProducerNode.java index 8be3d634..8ed55a33 100755 --- a/source/mircoders/producer/IndexingProducerNode.java +++ b/source/mircoders/producer/IndexingProducerNode.java @@ -29,40 +29,31 @@ */ package mircoders.producer; -import java.io.File; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.Map; - import mir.entity.Entity; import mir.entity.adapter.EntityAdapter; import mir.log.LoggerWrapper; import mir.misc.StringUtil; +import mir.producer.AbstractProducerNode; import mir.producer.ProducerFailure; -import mir.producer.ProducerNode; -import mir.util.FileFunctions; +import mir.util.FileRoutines; import mir.util.ParameterExpander; import mircoders.entity.EntityContent; -import mircoders.search.AudioSearchTerm; -import mircoders.search.ContentSearchTerm; -import mircoders.search.ImagesSearchTerm; -import mircoders.search.IndexUtil; -import mircoders.search.KeywordSearchTerm; -import mircoders.search.TextSearchTerm; -import mircoders.search.TopicSearchTerm; -import mircoders.search.UnIndexedSearchTerm; -import mircoders.search.VideoSearchTerm; - +import mircoders.search.*; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.store.FSDirectory; +import java.io.File; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.Map; + -public class IndexingProducerNode implements ProducerNode { +public class IndexingProducerNode extends AbstractProducerNode { private String contentKey; private String indexPath; private File indexBasePath; @@ -85,7 +76,7 @@ public class IndexingProducerNode implements ProducerNode { startTime = System.currentTimeMillis(); try { - indexFile = FileFunctions.getAbsoluteOrRelativeFile(indexBasePath, ParameterExpander.expandExpression(aValueMap, indexPath)); + indexFile = FileRoutines.getAbsoluteOrRelativeFile(indexBasePath, ParameterExpander.expandExpression(aValueMap, indexPath)); data = ParameterExpander.findValueForKey(aValueMap, contentKey); if (!(data instanceof EntityAdapter)) { @@ -102,11 +93,11 @@ public class IndexingProducerNode implements ProducerNode { entity.getClass().getName() + " adapter", null); } - aLogger.info("Indexing " + entity.getFieldValue("id") + " into " + indexFile.getAbsolutePath()); + aLogger.debug("Indexing " + entity.getFieldValue("id") + " into " + indexFile.getAbsolutePath()); // create an index here if one did not already exist if (!(IndexReader.indexExists(indexFile))) { - aLogger.error("Didn't find existing index, so I'm making one in " + indexFile.getAbsolutePath()); + aLogger.warn("Didn't find existing index, so I'm making one in " + indexFile.getAbsolutePath()); IndexWriter indexCreator = new IndexWriter(indexFile, new StandardAnalyzer(), true); indexCreator.close(); @@ -149,8 +140,7 @@ public class IndexingProducerNode implements ProducerNode { formattedDate = formatter.format(date); } catch (Throwable t) { - aLogger.error("Error while generating content date to index: " + t.getMessage()); - t.printStackTrace(aLogger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); + aLogger.warn("Error while generating content date to index", t); } } (new KeywordSearchTerm("webdb_create_formatted", "search_date", @@ -208,7 +198,7 @@ public class IndexingProducerNode implements ProducerNode { indexWriter.close(); } catch (Throwable t) { - aLogger.warn("Error while closing indexWriter: " + t.getMessage()); + aLogger.warn("Error while closing indexWriter", t); } } @@ -221,13 +211,13 @@ public class IndexingProducerNode implements ProducerNode { } } catch (Throwable t) { - aLogger.warn("Error while unlocking index: " + t.getMessage()); + aLogger.warn("Error while unlocking index", t); } } } endTime = System.currentTimeMillis(); - aLogger.info(" IndexTime: " + (endTime - startTime) + " ms
"); + aLogger.debug(" IndexTime: " + (endTime - startTime) + " ms
"); } } diff --git a/source/mircoders/producer/MediaGeneratingProducerNode.java b/source/mircoders/producer/MediaGeneratingProducerNode.java index 4d6f3d83..584cbeb8 100755 --- a/source/mircoders/producer/MediaGeneratingProducerNode.java +++ b/source/mircoders/producer/MediaGeneratingProducerNode.java @@ -30,20 +30,20 @@ package mircoders.producer; -import java.util.Map; - import mir.entity.Entity; import mir.entity.adapter.EntityAdapter; import mir.log.LoggerWrapper; import mir.media.MediaHandler; +import mir.producer.AbstractProducerNode; import mir.producer.ProducerExc; -import mir.producer.ProducerNode; import mir.util.ParameterExpander; import mircoders.entity.EntityUploadedMedia; import mircoders.media.MediaHelper; import mircoders.storage.DatabaseUploadedMedia; -public class MediaGeneratingProducerNode implements ProducerNode { +import java.util.Map; + +public class MediaGeneratingProducerNode extends AbstractProducerNode { private String mediaEntityKey; public MediaGeneratingProducerNode(String aMediaEntityKey) { diff --git a/source/mircoders/producer/PDFGeneratingProducerNode.java b/source/mircoders/producer/PDFGeneratingProducerNode.java deleted file mode 100755 index 4a6e7208..00000000 --- a/source/mircoders/producer/PDFGeneratingProducerNode.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * 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.producer; - -import java.util.Map; - -import mir.log.LoggerWrapper; -import mir.misc.PDFUtil; -import mir.producer.ProducerNode; -import mir.util.ParameterExpander; - -public class PDFGeneratingProducerNode implements ProducerNode { - private String generatorExpression; - private String destinationExpression; - private String stylesheet; - - public PDFGeneratingProducerNode(String aGenerator, String aDestination,String aStylesheet) { - generatorExpression=aGenerator; - destinationExpression=aDestination; - stylesheet=aStylesheet; - } - - public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) { - - String generatorIdentifier; - String destinationIdentifier; - String stylesheetIdentifier; - - long startTime; - long endTime; - - startTime = System.currentTimeMillis(); - try { - - destinationIdentifier = ParameterExpander.expandExpression( aValueMap, destinationExpression ); - generatorIdentifier = ParameterExpander.expandExpression( aValueMap, generatorExpression ); - stylesheetIdentifier = ParameterExpander.expandExpression( aValueMap, stylesheet); - - aLogger.info("Generating " + generatorIdentifier + " into " + destinationIdentifier + " using "+ stylesheetIdentifier); - - PDFUtil.makePDF(generatorIdentifier,destinationIdentifier,stylesheetIdentifier); - - } - catch (Throwable t) { - t.printStackTrace(aLogger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); - aLogger.error(" error while generating: " + t.getMessage() + t.toString()); - } - endTime = System.currentTimeMillis(); - - aLogger.info(" Time: " + (endTime-startTime) + " ms
"); - } -} - - - diff --git a/source/mircoders/producer/PDFPreFormattingProducerNode.java b/source/mircoders/producer/PDFPreFormattingProducerNode.java deleted file mode 100755 index 597872e8..00000000 --- a/source/mircoders/producer/PDFPreFormattingProducerNode.java +++ /dev/null @@ -1,235 +0,0 @@ -/* - * 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.producer; - -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import mir.entity.Entity; -import mir.entity.EntityBrowser; -import mir.entity.adapter.EntityAdapter; -import mir.log.LoggerToWriterAdapter; -import mir.log.LoggerWrapper; -import mir.misc.StringUtil; -import mir.producer.ProducerFailure; -import mir.producer.ProducerNode; -import mir.util.CachingRewindableIterator; -import mir.util.HTMLRoutines; -import mir.util.ParameterExpander; -import mircoders.entity.EntityContent; -import mircoders.entity.EntityImages; -import mircoders.storage.DatabaseImages; - - -public class PDFPreFormattingProducerNode implements ProducerNode { - private String contentKey; - private int numLinesBetweenImages; - private float contentAreaWidthCM; - private float characterWidthCM; - private float pixelWidthCM; - private float lineHeightCM; - - public PDFPreFormattingProducerNode(String aContentKey,String someNumLinesBetweenImages,String aContentAreaWidthCM,String aCharacterWidthCM,String aPixelWidthCM,String aLineHeightCM) { - contentKey = aContentKey; - numLinesBetweenImages=(new Integer(someNumLinesBetweenImages)).intValue(); - contentAreaWidthCM=(new Float(aContentAreaWidthCM)).floatValue(); - characterWidthCM=(new Float(aCharacterWidthCM)).floatValue(); - pixelWidthCM=(new Float(aPixelWidthCM)).floatValue(); - lineHeightCM=(new Float(aLineHeightCM)).floatValue(); - - // float characterWidthCM = 0.17F; - //float contentAreaWidthCM = 16; - //float pixelWidthCM = .03F; - //float lineHeightCM = .5F; - } - - public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure { - Object data; - Entity entity; - - try { - data = ParameterExpander.findValueForKey( aValueMap, contentKey ); - - if (! (data instanceof EntityAdapter)) { - throw new ProducerFailure("PDFPreFormattingProducerNode: value of '"+contentKey+"' is not an EntityAdapter, but an " + data.getClass().getName(), null); - } - - entity = ((EntityAdapter) data).getEntity(); - if (! (entity instanceof EntityContent)) { - throw new ProducerFailure("PDFPreFormattingProducerNode: value of '"+contentKey+"' is not a content EntityAdapter, but a " + entity.getClass().getName() + " adapter", null); - } - - int currentPosition = 0; - - //int numLinesBetweenImages=3; - - - - - int numCharsInAnImagelessRow = (new Float(numLinesBetweenImages * (contentAreaWidthCM/characterWidthCM))).intValue(); - - boolean outOfText = false; - - ArrayList brokenUpContent = new ArrayList(); - - - List extraTables = new ArrayList(); - extraTables.add("content_x_media cxm"); - Iterator images = new EntityBrowser( - DatabaseImages.getInstance(), "i", extraTables, - "cxm.content_id="+entity.getId()+"and cxm.media_id=i.id", - "i.id desc", 30, -1, 0); - - String theContent = ((EntityContent) entity).getFieldValue("content_data"); - //remove pesky characters - theContent = HTMLRoutines.encodeXML(theContent); - //put in the
tags so we can turn them to empty blocks - theContent = StringUtil.convertNewline2Break(theContent); - - if (images == null){ - Map row = new HashMap(); - row.put("text",theContent); - row.put("hasImage","0"); - brokenUpContent.add(row); - } - if (images != null){ - //need to add checks for out of content! - Map row0 = new HashMap(); - if (numCharsInAnImagelessRow>(theContent).length()){ - row0.put("text",theContent); - outOfText = true; - } - else { - //break on words so we don't split html entities - int lastSpaceAt = theContent.lastIndexOf(" ",numCharsInAnImagelessRow); - row0.put("text",theContent.substring(0,lastSpaceAt)); - currentPosition=lastSpaceAt; - } - row0.put("hasImage","0"); - brokenUpContent.add(row0); - aLogger.debug("CP1 is "+ currentPosition); - while(images.hasNext()){ - Map row1 = new HashMap(); - Map row2 = new HashMap(); - EntityImages currentImage=(EntityImages) images.next(); - float img_width=(new Float(currentImage.getFieldValue("img_width"))).floatValue(); - float img_height=(new Float(currentImage.getFieldValue("img_height"))).floatValue(); - - //oversize images must be shrunk - if (img_width>250){ - img_height=(new Float((new Float(img_height*(250.0F/img_width))).intValue())).floatValue(); - img_width=250.0F; - } - - - //calculate how much text goes in the column(use 8 pixels to pad the column) - float text_widthCM = contentAreaWidthCM-((img_width+8)*pixelWidthCM); - float number_of_lines = img_height*pixelWidthCM/lineHeightCM; //don't worry we will make it an int - //add one line for image description - int text_amount= (new Float((text_widthCM/characterWidthCM)*(number_of_lines+1))).intValue(); - - row1.put("text_widthCM",Float.toString(text_widthCM)); - - row1.put("img_title",currentImage.getFieldValue("title")); - - row1.put("img_width",Float.toString(img_width)); - row1.put("img_height",Float.toString(img_height)); - - aLogger.debug("img_width " +Float.toString(img_width)); - aLogger.debug("img_height "+Float.toString(img_height)); - - row1.put("img_src",currentImage.getFieldValue("publish_path")); - row1.put("hasImage","1"); - if (! outOfText){ - try { - int lastSpaceAt = theContent.lastIndexOf(" ",currentPosition+text_amount); - row1.put("text",theContent.substring(currentPosition,lastSpaceAt)); - currentPosition=lastSpaceAt; - } - catch (IndexOutOfBoundsException e){ - row1.put("text",theContent.substring(currentPosition)); - outOfText = true; - } - } - aLogger.debug("CP2 is "+ currentPosition); - brokenUpContent.add(row1); - - if (! outOfText){ - try { - int lastSpaceAt = theContent.lastIndexOf(" ",currentPosition+numCharsInAnImagelessRow); - row2.put("text",theContent.substring(currentPosition,lastSpaceAt)); - currentPosition=lastSpaceAt; - } - catch (IndexOutOfBoundsException e){ - row2.put("text",theContent.substring(currentPosition)); - outOfText = true; - } - } - row2.put("hasImage","0"); - brokenUpContent.add(row2); - - aLogger.debug("CP3 is "+ currentPosition); - } - Map row3 = new HashMap(); - if (! outOfText){ - row3.put("text",theContent.substring(currentPosition)); - row3.put("hasImage","0"); - brokenUpContent.add(row3); - } - - } - - - - - - ParameterExpander.setValueForKey( - aValueMap, - "data.formatted_content", - new CachingRewindableIterator(brokenUpContent.iterator()) - ); - - - } - catch (Throwable t) { - aLogger.error("Error while formatting content for PDF: " + t.getMessage()); - t.printStackTrace(new PrintWriter(new LoggerToWriterAdapter(aLogger, LoggerWrapper.DEBUG_MESSAGE))); - } - } -} - - - - diff --git a/source/mircoders/producer/RadicalendarProducerNode.java b/source/mircoders/producer/RadicalendarProducerNode.java index 3990b6d2..4e9e8b39 100755 --- a/source/mircoders/producer/RadicalendarProducerNode.java +++ b/source/mircoders/producer/RadicalendarProducerNode.java @@ -29,24 +29,17 @@ */ package mircoders.producer; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.Map; -import java.util.Vector; - import mir.log.LoggerWrapper; +import mir.producer.AbstractProducerNode; import mir.producer.ProducerFailure; -import mir.producer.ProducerNode; -import mir.util.ExceptionFunctions; +import mir.util.ExceptionRoutines; import mir.util.ParameterExpander; - import org.apache.xmlrpc.XmlRpcClient; +import java.util.*; + -public class RadicalendarProducerNode implements ProducerNode { +public class RadicalendarProducerNode extends AbstractProducerNode { private String key; private String groupname; private String gmtoffset; @@ -103,7 +96,7 @@ public class RadicalendarProducerNode implements ProducerNode { ); } catch (Throwable t) { - Throwable s = ExceptionFunctions.traceCauseException(t); + Throwable s = ExceptionRoutines.traceCauseException(t); aLogger.error("Error while accessing radicalendar: " + s.getClass().getName()+","+ s.getMessage()); } } diff --git a/source/mircoders/producer/UnIndexingProducerNode.java b/source/mircoders/producer/UnIndexingProducerNode.java index 5e241156..cf26e155 100755 --- a/source/mircoders/producer/UnIndexingProducerNode.java +++ b/source/mircoders/producer/UnIndexingProducerNode.java @@ -29,19 +29,19 @@ */ package mircoders.producer; -import java.io.File; -import java.util.Map; - import mir.entity.Entity; import mir.entity.adapter.EntityAdapter; import mir.log.LoggerWrapper; import mir.producer.ProducerFailure; import mir.producer.ProducerNode; -import mir.util.FileFunctions; +import mir.producer.ProductionContext; +import mir.util.FileRoutines; import mir.util.ParameterExpander; import mircoders.entity.EntityContent; import mircoders.search.IndexUtil; +import java.io.File; + /** * UnIndexingProducerNode is one of the 2 producer nodes that works on * the search index db. There's IndexingProducerNode and @@ -59,7 +59,7 @@ public class UnIndexingProducerNode implements ProducerNode { indexBasePath = anIndexBasePath; } - public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure { + public void produce(ProductionContext aProductionContext) throws ProducerFailure { Object data; Entity entity; File indexFile; @@ -70,9 +70,10 @@ public class UnIndexingProducerNode implements ProducerNode { startTime = System.currentTimeMillis(); try { - indexFile = FileFunctions.getAbsoluteOrRelativeFile(indexBasePath, ParameterExpander.expandExpression(aValueMap, indexPath)); + indexFile = FileRoutines.getAbsoluteOrRelativeFile(indexBasePath, + ParameterExpander.expandExpression(aProductionContext.getValueSet(), indexPath)); - data = ParameterExpander.findValueForKey( aValueMap, contentKey ); + data = ParameterExpander.findValueForKey(aProductionContext.getValueSet(), contentKey); if (! (data instanceof EntityAdapter)) { throw new ProducerFailure("UnIndexingProducerNode: value of '"+contentKey+"' is not an EntityAdapter, but an " + data.getClass().getName(), null); @@ -82,18 +83,18 @@ public class UnIndexingProducerNode implements ProducerNode { if (! (entity instanceof EntityContent)) { throw new ProducerFailure("UnIndexingProducerNode: value of '"+contentKey+"' is not a content EntityAdapter, but a " + entity.getClass().getName() + " adapter", null); } - aLogger.info("UnIndexing " + entity.getFieldValue("id") + " out of " + indexFile.getAbsolutePath()); + aProductionContext.getLogger().info("UnIndexing " + entity.getFieldValue("id") + " out of " + indexFile.getAbsolutePath()); IndexUtil.unindexEntity((EntityContent) entity, indexFile); } catch (Throwable t) { - aLogger.error("Error while unindexing content: " + t.getMessage()); - t.printStackTrace(aLogger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); + aProductionContext.getLogger().error("Error while unindexing content: " + t.getMessage()); + t.printStackTrace(aProductionContext.getLogger().asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); } endTime = System.currentTimeMillis(); - aLogger.info(" UnIndexTime: " + (endTime-startTime) + " ms
"); + aProductionContext.getLogger().info(" UnIndexTime: " + (endTime-startTime) + " ms
"); } } diff --git a/source/mircoders/producer/reader/SupplementalProducerNodeBuilders.java b/source/mircoders/producer/reader/SupplementalProducerNodeBuilders.java index a0a1a1c9..9a9b65cf 100755 --- a/source/mircoders/producer/reader/SupplementalProducerNodeBuilders.java +++ b/source/mircoders/producer/reader/SupplementalProducerNodeBuilders.java @@ -43,8 +43,6 @@ import mircoders.producer.ContentMarkingProducerNode; import mircoders.producer.ContentModifyingProducerNode; import mircoders.producer.IndexingProducerNode; import mircoders.producer.MediaGeneratingProducerNode; -import mircoders.producer.PDFGeneratingProducerNode; -import mircoders.producer.PDFPreFormattingProducerNode; import mircoders.producer.RadicalendarProducerNode; import mircoders.producer.UnIndexingProducerNode; @@ -58,14 +56,11 @@ public class SupplementalProducerNodeBuilders { aBuilderLibrary.registerFactory("IndexContent", new ContentIndexingProducerNodeBuilder.factory(aBasePath)); aBuilderLibrary.registerFactory("UnIndexContent", new ContentUnIndexingProducerNodeBuilder.factory(aBasePath)); - aBuilderLibrary.registerBuilder("PDFPreFormat", PDFPreFormattingProducerNodeBuilder.class); - aBuilderLibrary.registerBuilder("PDFGenerate", PDFGeneratingProducerNodeBuilder.class); aBuilderLibrary.registerBuilder("Radicalendar", RadicalendarProducerNodeBuilder.class); -// aBuilderLibrary.registerBuilder("ReportChangedFiles", ); } - private final static String MARKER_KEY_ATTRIBUTE = DefaultProducerNodeBuilders.KEY_ATTRIBUTE; - private final static String[] MARKER_REQUIRED_ATTRIBUTES = { MARKER_KEY_ATTRIBUTE }; + private final static String MARKER_KEY_ATTRIBUTE = DefaultProducerNodeBuilders.KEY_ATTRIBUTE; + private final static String[] MARKER_REQUIRED_ATTRIBUTES = {MARKER_KEY_ATTRIBUTE}; private final static String[] MARKER_OPTIONAL_ATTRIBUTES = {}; private final static String[] MARKER_SUBNODES = {}; @@ -87,9 +82,10 @@ public class SupplementalProducerNodeBuilders { return new ContentMarkingProducerNode(key); } } - private final static String INDEXER_KEY_ATTRIBUTE = DefaultProducerNodeBuilders.KEY_ATTRIBUTE; - private final static String INDEXER_INDEX_ATTRIBUTE = "pathToIndex"; - private final static String[] INDEXER_REQUIRED_ATTRIBUTES = { INDEXER_KEY_ATTRIBUTE, INDEXER_INDEX_ATTRIBUTE }; + + private final static String INDEXER_KEY_ATTRIBUTE = DefaultProducerNodeBuilders.KEY_ATTRIBUTE; + private final static String INDEXER_INDEX_ATTRIBUTE = "pathToIndex"; + private final static String[] INDEXER_REQUIRED_ATTRIBUTES = {INDEXER_KEY_ATTRIBUTE, INDEXER_INDEX_ATTRIBUTE}; private final static String[] INDEXER_OPTIONAL_ATTRIBUTES = {}; private final static String[] INDEXER_SUBNODES = {}; @@ -128,9 +124,9 @@ public class SupplementalProducerNodeBuilders { } } - private final static String UNINDEXER_KEY_ATTRIBUTE = DefaultProducerNodeBuilders.KEY_ATTRIBUTE; - private final static String UNINDEXER_INDEX_ATTRIBUTE = "pathToIndex"; - private final static String[] UNINDEXER_REQUIRED_ATTRIBUTES = { UNINDEXER_KEY_ATTRIBUTE, UNINDEXER_INDEX_ATTRIBUTE }; + private final static String UNINDEXER_KEY_ATTRIBUTE = DefaultProducerNodeBuilders.KEY_ATTRIBUTE; + private final static String UNINDEXER_INDEX_ATTRIBUTE = "pathToIndex"; + private final static String[] UNINDEXER_REQUIRED_ATTRIBUTES = {UNINDEXER_KEY_ATTRIBUTE, UNINDEXER_INDEX_ATTRIBUTE}; private final static String[] UNINDEXER_OPTIONAL_ATTRIBUTES = {}; private final static String[] UNINDEXER_SUBNODES = {}; @@ -166,14 +162,14 @@ public class SupplementalProducerNodeBuilders { } public ProducerNode constructNode() { - return new UnIndexingProducerNode(indexBasePath, key,pathToIndex); + return new UnIndexingProducerNode(indexBasePath, key, pathToIndex); } } - private final static String CONTENT_MODIFIER_KEY_ATTRIBUTE = DefaultProducerNodeBuilders.KEY_ATTRIBUTE; - private final static String CONTENT_MODIFIER_FIELD_ATTRIBUTE = "field"; - private final static String CONTENT_MODIFIER_VALUE_ATTRIBUTE = "value"; - private final static String[] CONTENT_MODIFIER_REQUIRED_ATTRIBUTES = { CONTENT_MODIFIER_KEY_ATTRIBUTE, CONTENT_MODIFIER_FIELD_ATTRIBUTE, CONTENT_MODIFIER_VALUE_ATTRIBUTE }; + private final static String CONTENT_MODIFIER_KEY_ATTRIBUTE = DefaultProducerNodeBuilders.KEY_ATTRIBUTE; + private final static String CONTENT_MODIFIER_FIELD_ATTRIBUTE = "field"; + private final static String CONTENT_MODIFIER_VALUE_ATTRIBUTE = "value"; + private final static String[] CONTENT_MODIFIER_REQUIRED_ATTRIBUTES = {CONTENT_MODIFIER_KEY_ATTRIBUTE, CONTENT_MODIFIER_FIELD_ATTRIBUTE, CONTENT_MODIFIER_VALUE_ATTRIBUTE}; private final static String[] CONTENT_MODIFIER_OPTIONAL_ATTRIBUTES = {}; private final static String[] CONTENT_MODIFIER_SUBNODES = {}; @@ -200,8 +196,8 @@ public class SupplementalProducerNodeBuilders { } } - private final static String MEDIA_KEY_ATTRIBUTE = DefaultProducerNodeBuilders.KEY_ATTRIBUTE; - private final static String[] MEDIA_REQUIRED_ATTRIBUTES = { MEDIA_KEY_ATTRIBUTE }; + private final static String MEDIA_KEY_ATTRIBUTE = DefaultProducerNodeBuilders.KEY_ATTRIBUTE; + private final static String[] MEDIA_REQUIRED_ATTRIBUTES = {MEDIA_KEY_ATTRIBUTE}; private final static String[] MEDIA_OPTIONAL_ATTRIBUTES = {}; private final static String[] MEDIA_SUBNODES = {}; @@ -224,144 +220,34 @@ public class SupplementalProducerNodeBuilders { } } - public static class PDFPreFormattingProducerNodeBuilder extends DefaultProducerNodeBuilders.AbstractProducerNodeBuilder { - private final static String MARKER_KEY_ATTRIBUTE = DefaultProducerNodeBuilders.KEY_ATTRIBUTE; - private final static String PDF_NUM_LINES_ATTRIBUTE = "numLinesBetweenImages"; - private final static String PDF_CONTENT_WIDTH_ATTRIBUTE = "contentAreaWidthCM"; - private final static String PDF_CHAR_WIDTH_ATTRIBUTE = "charWidthCM"; - private final static String PDF_PIXEL_WIDTH_ATTRIBUTE = "pixelWidthCM"; - private final static String PDF_LINE_HEIGHT_ATTRIBUTE = "lineHeightCM"; - private final static String[] MARKER_REQUIRED_ATTRIBUTES = { MARKER_KEY_ATTRIBUTE, PDF_NUM_LINES_ATTRIBUTE, PDF_CONTENT_WIDTH_ATTRIBUTE,PDF_CHAR_WIDTH_ATTRIBUTE,PDF_PIXEL_WIDTH_ATTRIBUTE,PDF_LINE_HEIGHT_ATTRIBUTE }; - private final static String[] MARKER_OPTIONAL_ATTRIBUTES = {}; - private final static String[] MARKER_SUBNODES = {}; - + public static class RadicalendarProducerNodeBuilder extends DefaultProducerNodeBuilders.AbstractProducerNodeBuilder { + private final static String RC_KEY_ATTRIBUTE = "key"; + private final static String RC_GROUPNAME_ATTRIBUTE = "groupname"; + private final static String RC_GMTOFFSET_ATTRIBUTE = "gmtoffset"; + private final static String[] RC_REQUIRED_ATTRIBUTES = {RC_KEY_ATTRIBUTE, RC_GROUPNAME_ATTRIBUTE, RC_GMTOFFSET_ATTRIBUTE}; + private final static String[] RC_OPTIONAL_ATTRIBUTES = {}; + private final static String[] RC_SUBNODES = {}; private String key; - private String numLinesBetweenImages; - private String contentAreaWidthCM; - private String characterWidthCM; - private String pixelWidthCM; - private String lineHeightCM; - - public PDFPreFormattingProducerNodeBuilder() { - super(MARKER_SUBNODES); - } - - public void setAttributes(Map anAttributes) throws ProducerConfigExc, XMLParserExc { - XMLReaderTool.checkAttributes(anAttributes, MARKER_REQUIRED_ATTRIBUTES, MARKER_OPTIONAL_ATTRIBUTES); - - key = (String) anAttributes.get(MARKER_KEY_ATTRIBUTE); - numLinesBetweenImages = (String) anAttributes.get(PDF_NUM_LINES_ATTRIBUTE); - contentAreaWidthCM = (String) anAttributes.get(PDF_CONTENT_WIDTH_ATTRIBUTE); - characterWidthCM = (String) anAttributes.get(PDF_CHAR_WIDTH_ATTRIBUTE); - pixelWidthCM = (String) anAttributes.get(PDF_PIXEL_WIDTH_ATTRIBUTE); - lineHeightCM = (String) anAttributes.get(PDF_LINE_HEIGHT_ATTRIBUTE); - } - - public ProducerNode constructNode() { - return new PDFPreFormattingProducerNode(key,numLinesBetweenImages,contentAreaWidthCM,characterWidthCM,pixelWidthCM,lineHeightCM); - } - } + private String groupname; + private String gmtoffset; - public static class PDFGeneratingProducerNodeBuilder extends DefaultProducerNodeBuilders.AbstractProducerNodeBuilder { - private final static String PDF_GENERATOR_ATTRIBUTE = "generator"; - private final static String PDF_DESTINATION_ATTRIBUTE = "destination"; - private final static String PDF_STYLESHEET_ATTRIBUTE = "stylesheet"; - private final static String[] MARKER_REQUIRED_ATTRIBUTES = {PDF_GENERATOR_ATTRIBUTE,PDF_DESTINATION_ATTRIBUTE,PDF_STYLESHEET_ATTRIBUTE }; - private final static String[] MARKER_OPTIONAL_ATTRIBUTES = {}; - private final static String[] MARKER_SUBNODES = {}; - - private String generator; - private String destination; - private String stylesheet; - - - public PDFGeneratingProducerNodeBuilder() { - super(MARKER_SUBNODES); + public RadicalendarProducerNodeBuilder() { + super(RC_SUBNODES); } public void setAttributes(Map anAttributes) throws ProducerConfigExc, XMLParserExc { - XMLReaderTool.checkAttributes(anAttributes, MARKER_REQUIRED_ATTRIBUTES, MARKER_OPTIONAL_ATTRIBUTES); + XMLReaderTool.checkAttributes(anAttributes, RC_REQUIRED_ATTRIBUTES, RC_OPTIONAL_ATTRIBUTES); - generator = (String) anAttributes.get(PDF_GENERATOR_ATTRIBUTE); - destination = (String) anAttributes.get(PDF_DESTINATION_ATTRIBUTE); - stylesheet = (String) anAttributes.get(PDF_STYLESHEET_ATTRIBUTE); + key = (String) anAttributes.get(RC_KEY_ATTRIBUTE); + groupname = (String) anAttributes.get(RC_GROUPNAME_ATTRIBUTE); + gmtoffset = (String) anAttributes.get(RC_GMTOFFSET_ATTRIBUTE); } public ProducerNode constructNode() { - return new PDFGeneratingProducerNode(generator,destination,stylesheet); + return new RadicalendarProducerNode(key, groupname, gmtoffset); } } - public static class RadicalendarProducerNodeBuilder extends DefaultProducerNodeBuilders.AbstractProducerNodeBuilder { - private final static String RC_KEY_ATTRIBUTE = "key"; - private final static String RC_GROUPNAME_ATTRIBUTE = "groupname"; - private final static String RC_GMTOFFSET_ATTRIBUTE = "gmtoffset"; - private final static String[] RC_REQUIRED_ATTRIBUTES = {RC_KEY_ATTRIBUTE,RC_GROUPNAME_ATTRIBUTE,RC_GMTOFFSET_ATTRIBUTE}; - private final static String[] RC_OPTIONAL_ATTRIBUTES = {}; - private final static String[] RC_SUBNODES = {}; - private String key; - private String groupname; - private String gmtoffset; - - public RadicalendarProducerNodeBuilder() { - super(RC_SUBNODES); - } - - public void setAttributes(Map anAttributes) throws ProducerConfigExc, XMLParserExc { - XMLReaderTool.checkAttributes(anAttributes, RC_REQUIRED_ATTRIBUTES, RC_OPTIONAL_ATTRIBUTES); - - key = (String) anAttributes.get(RC_KEY_ATTRIBUTE); - groupname = (String) anAttributes.get(RC_GROUPNAME_ATTRIBUTE); - gmtoffset = (String) anAttributes.get(RC_GMTOFFSET_ATTRIBUTE); - } - - public ProducerNode constructNode() { - return new RadicalendarProducerNode(key,groupname,gmtoffset); - } - - } - - - /** - * Builder for {@link mircoders.producer.ChangedFilesReportingProducerNode} - * nodes. - */ -/* - private static class ChangeReportingProducerNodeBuilder extends DefaultProducerNodeBuilders.AbstractProducerNodeBuilder { - private final static String DESTINATION_FILE_ATTRIBUTE = "reportFile"; - private final static String LOCK_FILE_ATTRIBUTE = "lockfile"; - private final static String BASE_PATH_ATTRIBUTE = "basepath"; - private final static String EXCLUDED_PATHS_ATTRIBUTE = "excludedpaths"; - private final static String FLUSH_ATTRIBUTE = "flush"; - private final static String[] REQUIRED_ATTRIBUTES = {DESTINATION_FILE_ATTRIBUTE}; - private final static String[] OPTIONAL_ATTRIBUTES = {LOCK_FILE_ATTRIBUTE, BASE_PATH_ATTRIBUTE, EXCLUDED_PATHS_ATTRIBUTE, FLUSH_ATTRIBUTE}; - private final static String[] SUBNODES = {}; - - private String reportFile; - private String lockFile; - private String basePath; - private String excludedPaths; - private String flush; - - public ChangeReportingProducerNodeBuilder() { - super(SUBNODES); - } - - public void setAttributes(Map anAttributes) throws ProducerConfigExc, XMLParserExc { - XMLReaderTool.checkAttributes(anAttributes, REQUIRED_ATTRIBUTES, OPTIONAL_ATTRIBUTES); - - reportFile = XMLReaderTool.getStringAttributeWithDefault(anAttributes, DESTINATION_FILE_ATTRIBUTE, null); - lockFile = XMLReaderTool.getStringAttributeWithDefault(anAttributes, LOCK_FILE_ATTRIBUTE, null); - basePath = XMLReaderTool.getStringAttributeWithDefault(anAttributes, BASE_PATH_ATTRIBUTE, ""); - excludedPaths = XMLReaderTool.getStringAttributeWithDefault(anAttributes, EXCLUDED_PATHS_ATTRIBUTE, ""); - flush = XMLReaderTool.getStringAttributeWithDefault(anAttributes, FLUSH_ATTRIBUTE, "1"); - }; - - public ProducerNode constructNode() { - return new ChangedFilesReportingProducerNode(reportFile, lockFile, basePath, excludedPaths, flush); - }; - } -*/ } diff --git a/source/mircoders/search/MediaSearchTerm.java b/source/mircoders/search/MediaSearchTerm.java deleted file mode 100755 index 5f38aebd..00000000 --- a/source/mircoders/search/MediaSearchTerm.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * 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.search; - -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; - -import mir.entity.Entity; -import mir.storage.DatabaseFailure; - -import org.apache.lucene.document.Document; - -/** - * not used - */ -public class MediaSearchTerm extends SearchTerm{ - public MediaSearchTerm() { - super(null, "search_hasMedia", "", null, ""); - } - - public void index(Document doc, Entity entity) throws DatabaseFailure{ - // only use this term for doing alternate queries on media - return; - } - - public String makeTerm(HttpServletRequest req){ - String wanted = req.getParameter(paramName); - if (wanted != null && (wanted.equals("hasImages") || wanted.equals("hasAudio") || wanted.equals("hasVideo") )){ - return wanted + ":\"y\""; - } - return null; - } - - public void returnMeta(Map result,Document doc){ - return; - } - - -} - - diff --git a/source/mircoders/servlet/ServletModuleComment.java b/source/mircoders/servlet/ServletModuleComment.java index 74089d33..eff08cd9 100755 --- a/source/mircoders/servlet/ServletModuleComment.java +++ b/source/mircoders/servlet/ServletModuleComment.java @@ -99,7 +99,7 @@ public class ServletModuleComment extends ServletModule HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)}); EntityAdapterModel model = MirGlobal.localizer().dataModel().adapterModel(); - Map comment; + Object comment; URLBuilder urlBuilder = new URLBuilder(); urlBuilder.setValue("module", "Comment"); @@ -114,11 +114,13 @@ public class ServletModuleComment extends ServletModule else { List fields = DatabaseComment.getInstance().getFieldNames(); responseData.put("new", Boolean.TRUE); - comment = new HashMap(); + Map emptyComment = new HashMap(); Iterator i = fields.iterator(); while (i.hasNext()) { - comment.put(i.next(), null); + emptyComment.put(i.next(), null); } + + comment = emptyComment; } responseData.put("comment", comment); diff --git a/source/mircoders/servlet/ServletModuleContent.java b/source/mircoders/servlet/ServletModuleContent.java index afba80cd..13698884 100755 --- a/source/mircoders/servlet/ServletModuleContent.java +++ b/source/mircoders/servlet/ServletModuleContent.java @@ -354,7 +354,7 @@ public class ServletModuleContent extends ServletModule { HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}); EntityAdapterModel model = MirGlobal.localizer().dataModel().adapterModel(); - Map article; + Object article; URLBuilder urlBuilder = new URLBuilder(); urlBuilder.setValue("module", "Content"); @@ -376,20 +376,22 @@ public class ServletModuleContent extends ServletModule { else { List fields = DatabaseContent.getInstance().getFieldNames(); responseData.put("new", Boolean.TRUE); - article = new HashMap(); + Map emptyArticle = new HashMap(); Iterator i = fields.iterator(); while (i.hasNext()) { - article.put(i.next(), null); + emptyArticle.put(i.next(), null); } - article.put("to_topics", null); + emptyArticle.put("to_topics", null); - MirGlobal.localizer().adminInterface().initializeArticle(article); + MirGlobal.localizer().adminInterface().initializeArticle(emptyArticle); + article = emptyArticle; responseData.put("mayEdit", Boolean.TRUE); responseData.put("mayLock", Boolean.FALSE); responseData.put("mayForceLock", Boolean.FALSE); responseData.put("mayUnlock", Boolean.FALSE); + } responseData.put("article", article); diff --git a/source/mircoders/servlet/ServletModuleFileEdit.java b/source/mircoders/servlet/ServletModuleFileEdit.java index 93033474..b74a6002 100755 --- a/source/mircoders/servlet/ServletModuleFileEdit.java +++ b/source/mircoders/servlet/ServletModuleFileEdit.java @@ -50,7 +50,7 @@ import mir.log.LoggerWrapper; import mir.servlet.ServletModule; import mir.servlet.ServletModuleExc; import mir.servlet.ServletModuleFailure; -import mir.util.FileFunctions; +import mir.util.FileRoutines; import mir.util.HTTPRequestParser; import mir.util.StringRoutines; import mir.util.URLBuilder; @@ -60,8 +60,8 @@ import mir.util.URLBuilder; * Allows one to do a basic edit of a file in a directory specified * in the config file. * - * @author $Author: rhindes $ - * @version $Revision: 1.13.2.9 $ $Date: 2005/02/10 16:22:27 $ + * @author $Author: zapata $ + * @version $Revision: 1.13.2.10 $ $Date: 2005/08/21 17:09:24 $ * */ @@ -77,14 +77,14 @@ public class ServletModuleFileEdit extends ServletModule private class FileEditDirectory { private String name; - private FileFunctions.RegExpFileFilter filter; + private FileRoutines.RegExpFileFilter filter; private File rootDirectory; private boolean recursive; public FileEditDirectory(String aName, String aRootDirectory, String aFilter, boolean aRecursive) { name = aName; rootDirectory = new File(aRootDirectory); - filter = new FileFunctions.RegExpFileFilter(aFilter); + filter = new FileRoutines.RegExpFileFilter(aFilter); recursive = aRecursive; } @@ -92,7 +92,7 @@ public class ServletModuleFileEdit extends ServletModule return name; } - public FileFunctions.RegExpFileFilter getFilter() { + public FileRoutines.RegExpFileFilter getFilter() { return filter; } @@ -138,7 +138,7 @@ public class ServletModuleFileEdit extends ServletModule } } - dirFilter = new FileFunctions.DirectoryFilter(); + dirFilter = new FileRoutines.DirectoryFilter(); } public List getEntries() { @@ -244,14 +244,14 @@ public class ServletModuleFileEdit extends ServletModule aSubDirectory = ""; } - responseData.put("filelist", FileFunctions.getDirectoryContentsAsList(dir, aDirectory.getFilter())); + responseData.put("filelist", FileRoutines.getDirectoryContentsAsList(dir, aDirectory.getFilter())); if (aDirectory.getRecursive()) { List dirs = new ArrayList(); if (!dir.getCanonicalPath().equals(aDirectory.getRootDirectory().getCanonicalPath())) responseData.put("updir", new File(aSubDirectory).getParent()); - dirs.addAll(FileFunctions.getDirectoryContentsAsList(dir, dirFilter)); + dirs.addAll(FileRoutines.getDirectoryContentsAsList(dir, dirFilter)); responseData.put("dirlist", dirs); } @@ -270,8 +270,7 @@ public class ServletModuleFileEdit extends ServletModule } } - public void editFile(FileEditDirectory aDirectory, String aFileName, String aSubDirectory, HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { + public void editFile(FileEditDirectory aDirectory, String aFileName, String aSubDirectory, HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { try { File f = new File(new File(aDirectory.getRootDirectory(), aSubDirectory), aFileName); @@ -295,8 +294,9 @@ public class ServletModuleFileEdit extends ServletModule // TODO read array char[] c = new char[4096]; int read; - while ( (read=in.read(c)) != -1) + while ((read=in.read(c)) != -1) { out.write(c, 0, read); + } in.close(); out.close(); diff --git a/source/mircoders/servlet/ServletModuleOpenIndy.java b/source/mircoders/servlet/ServletModuleOpenIndy.java index 0b54e64d..ea91bf08 100755 --- a/source/mircoders/servlet/ServletModuleOpenIndy.java +++ b/source/mircoders/servlet/ServletModuleOpenIndy.java @@ -32,29 +32,6 @@ package mircoders.servlet; import gnu.regexp.RE; import gnu.regexp.REMatch; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringWriter; -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.ListIterator; -import java.util.Locale; -import java.util.Map; -import java.util.Random; -import java.util.Set; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - import mir.bundle.Bundle; import mir.entity.Entity; import mir.generator.Generator; @@ -64,18 +41,9 @@ import mir.servlet.ServletModule; import mir.servlet.ServletModuleExc; import mir.servlet.ServletModuleFailure; import mir.servlet.ServletModuleUserExc; -import mir.session.HTTPAdapters; -import mir.session.Request; -import mir.session.Session; -import mir.session.SessionHandler; -import mir.session.SimpleResponse; -import mir.session.UploadedFile; +import mir.session.*; import mir.storage.DatabaseFailure; -import mir.util.ExceptionFunctions; -import mir.util.FileFunctions; -import mir.util.HTTPParsedRequest; -import mir.util.HTTPRequestParser; -import mir.util.StringRoutines; +import mir.util.*; import mircoders.entity.EntityComment; import mircoders.entity.EntityContent; import mircoders.global.CacheKey; @@ -85,34 +53,25 @@ import mircoders.media.UnsupportedMediaTypeExc; import mircoders.module.ModuleComment; import mircoders.module.ModuleContent; import mircoders.pdf.PDFGenerator; -import mircoders.search.AudioSearchTerm; -import mircoders.search.ContentSearchTerm; -import mircoders.search.ImagesSearchTerm; -import mircoders.search.KeywordSearchTerm; -import mircoders.search.TextSearchTerm; -import mircoders.search.TopicMatrixSearchTerm; -import mircoders.search.TopicSearchTerm; -import mircoders.search.UnIndexedSearchTerm; -import mircoders.search.VideoSearchTerm; -import mircoders.storage.DatabaseComment; -import mircoders.storage.DatabaseContent; -import mircoders.storage.DatabaseContentToMedia; -import mircoders.storage.DatabaseContentToTopics; -import mircoders.storage.DatabaseLanguage; -import mircoders.storage.DatabaseTopics; - +import mircoders.search.*; +import mircoders.storage.*; import org.apache.commons.fileupload.FileItem; import org.apache.commons.net.smtp.SMTPClient; import org.apache.commons.net.smtp.SMTPReply; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; -import org.apache.lucene.index.IndexReader; -import org.apache.lucene.store.FSDirectory; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.search.Hits; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.Searcher; +import org.apache.lucene.store.FSDirectory; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import java.io.*; +import java.util.*; /* * ServletModuleOpenIndy - @@ -121,7 +80,7 @@ import org.apache.lucene.search.Searcher; * open-postings to the newswire * * @author mir-coders group - * @version $Id: ServletModuleOpenIndy.java,v 1.89.2.17 2005/03/26 11:26:27 zapata Exp $ + * @version $Id: ServletModuleOpenIndy.java,v 1.89.2.18 2005/08/21 17:09:24 zapata Exp $ * */ @@ -507,7 +466,7 @@ public class ServletModuleOpenIndy extends ServletModule } catch (Throwable e) { e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); - Throwable cause = ExceptionFunctions.traceCauseException(e); + Throwable cause = ExceptionRoutines.traceCauseException(e); if (cause instanceof UnsupportedMediaTypeExc) { throw new ServletModuleUserExc("media.unsupportedformat", new String[] {}); @@ -799,7 +758,7 @@ public class ServletModuleOpenIndy extends ServletModule session.setAttribute("positionInResults", new Integer(newPosition)); } else { - File indexFile = FileFunctions.getAbsoluteOrRelativeFile(configuration.getHome(), configuration.getString("IndexPath")); + File indexFile = FileRoutines.getAbsoluteOrRelativeFile(configuration.getHome(), configuration.getString("IndexPath")); String creatorFragment = creatorTerm.makeTerm(req); if (creatorFragment != null) { @@ -1160,7 +1119,7 @@ public class ServletModuleOpenIndy extends ServletModule public void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse,PrintWriter out, Throwable anException) { try { - logger.error("error: " + anException); + logger.error("Error during open action", anException); Map data = new HashMap(); data.put("errorstring", anException.getMessage()); diff --git a/source/mircoders/servlet/ServletModuleUploadedMedia.java b/source/mircoders/servlet/ServletModuleUploadedMedia.java index 0f42987e..d40eb376 100755 --- a/source/mircoders/servlet/ServletModuleUploadedMedia.java +++ b/source/mircoders/servlet/ServletModuleUploadedMedia.java @@ -160,7 +160,7 @@ public abstract class ServletModuleUploadedMedia extends ServletModule { returnUploadedMediaList(aRequest, aResponse, mediaList, 1, mediaList.size(), "", null, null); } catch (Throwable t) { - Throwable cause = ExceptionFunctions.traceCauseException(t); + Throwable cause = ExceptionRoutines.traceCauseException(t); if (cause instanceof UnsupportedMediaTypeExc) { throw new ServletModuleUserExc("media.error.unsupportedformat", new String[] {}); diff --git a/source/mircoders/servlet/ServletModuleUsers.java b/source/mircoders/servlet/ServletModuleUsers.java index 55993ee2..4d29ed4f 100755 --- a/source/mircoders/servlet/ServletModuleUsers.java +++ b/source/mircoders/servlet/ServletModuleUsers.java @@ -291,7 +291,7 @@ public class ServletModuleUsers extends ServletModule HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}); EntityAdapterModel model = MirGlobal.localizer().dataModel().adapterModel(); - Map user; + Object user; URLBuilder urlBuilder = new URLBuilder(); urlBuilder.setValue("module", "Users"); @@ -309,13 +309,13 @@ public class ServletModuleUsers extends ServletModule else { List fields = DatabaseUsers.getInstance().getFieldNames(); responseData.put("new", Boolean.TRUE); - user = new HashMap(); + Map emptyUser = new HashMap(); Iterator i = fields.iterator(); while (i.hasNext()) { - user.put(i.next(), null); + emptyUser.put(i.next(), null); } - MirGlobal.localizer().adminInterface().initializeArticle(user); + user = emptyUser; } responseData.put("user", user); responseData.put("passwordonly", new Boolean(anOnlyPassword)); diff --git a/source/tool/BundleTool.java b/source/tool/BundleTool.java index 9a766432..d8dcf9fa 100755 --- a/source/tool/BundleTool.java +++ b/source/tool/BundleTool.java @@ -40,7 +40,7 @@ import java.util.Arrays; import java.util.Iterator; import java.util.List; -import mir.util.ExceptionFunctions; +import mir.util.ExceptionRoutines; import mir.util.PropertiesManipulator; public class BundleTool { @@ -222,7 +222,7 @@ public class BundleTool { new FileInputStream(new File(aSourceFile)),8192), anEncoding); } catch (Throwable t) { - Throwable s = ExceptionFunctions.traceCauseException(t); + Throwable s = ExceptionRoutines.traceCauseException(t); System.out.println("Unable to read sourcefile: " + s.toString()); return; diff --git a/source/tool/ImageTool.java b/source/tool/ImageTool.java deleted file mode 100755 index beadd1c1..00000000 --- a/source/tool/ImageTool.java +++ /dev/null @@ -1,118 +0,0 @@ -package tool; - -import java.awt.Transparency; -import java.awt.image.ColorModel; -import java.awt.image.DataBuffer; -import java.awt.image.SampleModel; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; - -import javax.media.jai.JAI; -import javax.media.jai.PlanarImage; - - -/** - * This class displays basic information about the image. - */ -public class ImageTool { - /** - * The application entry point. - * @param args the command line arguments. - */ - public static void main(String[] args) throws FileNotFoundException { - // We need one argument: the image filename. - if (args.length != 1) { - System.err.println("Usage: java tool.ImageTool image"); - System.exit(0); - } - FileInputStream fi = new FileInputStream(args[0]); - // Open the image (using the name passed as a command line parameter) - PlanarImage pi = JAI.create("ImageRead", fi); - - // Display image data. First, the image size (non-JAI related). - File image = new File(args[0]); - System.out.println("Image file size:" + image.length() + " bytes."); - - // Now let's display the image dimensions and coordinates. - System.out.print("Dimensions: "); - System.out.print(pi.getWidth() + "x" + pi.getHeight() + " pixels"); - System.out.println(" (from " + pi.getMinX() + "," + pi.getMinY() + " to " + - pi.getMaxX() + "," + pi.getMaxY() + ")"); - - // Tiles number, dimensions and coordinates. - System.out.print("Tiles:"); - System.out.print(pi.getTileWidth() + "x" + pi.getTileHeight() + " pixels" + - " (" + pi.getNumXTiles() + "x" + pi.getNumYTiles() + - " tiles)"); - System.out.print(" (from " + pi.getMinTileX() + "," + pi.getMinTileY() + - " to " + pi.getMaxTileX() + "," + pi.getMaxTileY() + ")"); - System.out.println(" offset: " + pi.getTileGridXOffset() + "," + - pi.getTileGridXOffset()); - - // Display info about the SampleModel of the image. - SampleModel sm = pi.getSampleModel(); - System.out.println("Number of bands: " + sm.getNumBands()); - System.out.print("Data type: "); - - switch (sm.getDataType()) { - case DataBuffer.TYPE_BYTE: - System.out.println("byte"); - - break; - - case DataBuffer.TYPE_SHORT: - System.out.println("short"); - - break; - - case DataBuffer.TYPE_USHORT: - System.out.println("unsigned short"); - - break; - - case DataBuffer.TYPE_INT: - System.out.println("int"); - - break; - - case DataBuffer.TYPE_FLOAT: - System.out.println("float"); - - break; - - case DataBuffer.TYPE_DOUBLE: - System.out.println("double"); - - break; - - case DataBuffer.TYPE_UNDEFINED: - System.out.println("undefined"); - - break; - } - - // Display info about the ColorModel of the image. - ColorModel cm = pi.getColorModel(); - System.out.println("Number of color components: " + cm.getNumComponents()); - System.out.println("Bits per pixel: " + cm.getPixelSize()); - System.out.print("Transparency: "); - - switch (cm.getTransparency()) { - case Transparency.OPAQUE: - System.out.println("opaque"); - - break; - - case Transparency.BITMASK: - System.out.println("bitmask"); - - break; - - case Transparency.TRANSLUCENT: - System.out.println("translucent"); - - break; - } - } -}