From 2b0e1c1d91eea7e201af61e1065ad12bf966d1ba Mon Sep 17 00:00:00 2001 From: idfx Date: Sat, 6 Nov 2004 19:14:13 +0000 Subject: [PATCH] rebuilding head --- source/mir/bundle/BasicBundleFactory.java | 86 + .../HTMLParseException.java => bundle/Bundle.java} | 34 +- source/mir/bundle/BundleFactory.java | 42 + source/mir/bundle/BundleLoader.java | 52 + source/mir/bundle/CascadingBundleFactory.java | 70 + .../PropertiesBundle.java} | 89 +- source/mir/bundle/PropertiesFileBundleLoader.java | 67 + source/mir/config/MirPropertiesConfiguration.java | 138 +- source/mir/entity/AbstractEntity.java | 164 ++ source/mir/entity/Entity.java | 190 +- source/mir/entity/EntityBrowser.java | 33 +- source/mir/entity/EntityList.java | 521 ++-- source/mir/entity/GenericEntity.java | 16 +- source/mir/entity/StorableObjectEntity.java | 46 +- source/mir/entity/adapter/EntityAdapter.java | 43 +- .../entity/adapter/EntityAdapterDefinition.java | 72 +- source/mir/entity/adapter/EntityAdapterEngine.java | 140 +- .../mir/entity/adapter/EntityIteratorAdapter.java | 24 +- source/mir/entity/adapter/EntityListAdapter.java | 242 +- .../mir/generator/CompositeGeneratorLibrary.java | 10 +- source/mir/generator/FreemarkerGenerator.java | 60 +- source/mir/generator/Generator.java | 18 +- source/mir/generator/GeneratorHelper.java | 83 + .../mir/generator/GeneratorLibraryRepository.java | 51 +- source/mir/generator/TALGenerator.java | 115 + source/mir/generator/VelocityGenerator.java | 596 ++++ source/mir/generator/tal/CachingFileLoader.java | 138 + source/mir/generator/tal/MirExpressionParser.java | 154 + .../tal/SimpleTemplateNodeLibraryRegistry.java} | 68 +- source/mir/generator/tal/TALExc.java | 38 + source/mir/generator/tal/TALFailure.java | 42 + source/mir/generator/tal/TALTemplateEngine.java | 116 + source/mir/generator/tal/TALTemplateParser.java | 223 ++ source/mir/generator/tal/TALTest.java | 116 + .../tal/interfaces/TALExpressionParser.java | 69 + source/mir/generator/tal/interfaces/TALLogger.java | 87 + .../tal/template/CompositeTemplateNode.java | 98 + .../tal/template/CoreTemplateNodeLibrary.java | 380 +++ .../tal/template/MacroTemplateNodeLibrary.java | 207 ++ .../tal/template/PlainTextTemplateNode.java | 77 + source/mir/generator/tal/template/Template.java | 68 + .../generator/tal/template/TemplateLibrary.java | 41 + .../mir/generator/tal/template/TemplateNode.java | 52 + .../tal/template/TemplateNodeLibrary.java | 49 + .../tal/template/TemplateNodeLibraryRegistry.java | 35 + .../tal/template/TemplateProcessingException.java | 52 + source/mir/log/Logger.java | 16 +- source/mir/log/{Log.java => LoggerEngine.java} | 45 +- .../mir/log/{TestFramework.java => LoggerExc.java} | 27 +- source/mir/log/LoggerFailure.java | 43 + source/mir/log/LoggerWrapper.java | 24 +- source/mir/log/log4j/LoggerImpl.java | 48 +- .../mir/media/{MirMedia.java => MediaHandler.java} | 108 +- source/mir/misc/FileUtil.java | 48 +- source/mir/misc/LineFilterWriter.java | 96 - source/mir/misc/PDFUtil.java | 3 +- source/mir/misc/StringUtil.java | 878 +++--- source/mir/module/AbstractModule.java | 120 +- ...leProducerNode.java => BundleProducerNode.java} | 62 +- source/mir/producer/CompositeProducerNode.java | 18 +- source/mir/producer/DirCopyingProducerNode.java | 22 +- .../mir/producer/EntityBatchingProducerNode.java | 23 +- .../mir/producer/EntityDeletingProducerNode.java | 3 - .../producer/EntityEnumeratingProducerNode.java | 25 +- source/mir/producer/EntityListProducerNode.java | 86 +- .../mir/producer/EntityModifyingProducerNode.java | 13 +- .../mir/producer/ExecuteProgramProducerNode.java | 128 + source/mir/producer/ExternalDbProducerNode.java | 120 + .../mir/producer/FileDateSettingProducerNode.java | 17 +- source/mir/producer/GeneratingProducerNode.java | 60 +- .../mir/producer/ListEnumeratingProducerNode.java | 8 +- source/mir/producer/ProducerFactory.java | 34 +- source/mir/producer/ProducerNode.java | 22 +- source/mir/producer/RDFAggregatorProducerNode.java | 5 +- source/mir/producer/RSSProducerNode.java | 35 +- .../reader/DefaultProducerNodeBuilders.java | 245 +- .../mir/producer/reader/ProducerConfigReader.java | 190 +- .../mir/producer/reader/ProducerNodeBuilder.java | 20 +- .../producer/reader/ScriptedProducerFactory.java | 22 +- source/mir/rss/RDFResource.java | 2 +- source/mir/rss/RSS091Reader.java | 136 +- source/mir/rss/RSSAggregator.java | 6 +- source/mir/rss/RSSData.java | 6 +- source/mir/rss/RSSReader.java | 189 +- source/mir/rss/RSSTest.java | 76 - source/mir/servlet/AbstractServlet.java | 512 ++-- source/mir/servlet/ServletModule.java | 997 ++++--- source/mir/session/CommonsUploadedFileAdapter.java | 24 +- source/mir/session/HTTPAdapters.java | 328 ++- source/mir/session/Request.java | 1 + source/mir/session/UploadedFile.java | 31 +- source/mir/session/ValidationHelper.java | 3 - source/mir/storage/Database.java | 2935 ++++++++++---------- source/mir/storage/StorageObject.java | 196 +- source/mir/storage/store/ObjectStore.java | 40 +- source/mir/storage/store/StoreContainer.java | 12 +- source/mir/storage/store/StoreContainerType.java | 27 +- source/mir/storage/store/StoreIdentifier.java | 14 +- source/mir/storage/store/StoreUtil.java | 46 +- source/mir/util/CachingRewindableIterator.java | 17 +- source/mir/util/DateTimeFunctions.java | 1 - .../EntityUtility.java} | 121 +- source/mir/util/ExceptionFunctions.java | 13 +- source/mir/util/FileFunctions.java | 82 +- source/mir/util/GeneratorDateTimeFunctions.java | 6 +- source/mir/util/GeneratorFormatAdapters.java | 8 +- source/mir/util/GeneratorHTMLFunctions.java | 118 - source/mir/util/GeneratorIntegerFunctions.java | 80 - source/mir/util/GeneratorListFunctions.java | 87 - source/mir/util/GeneratorStringFunctions.java | 103 - source/mir/util/HTMLRoutines.java | 155 +- source/mir/util/HTTPClientHelper.java | 74 + source/mir/util/HTTPParsedRequest.java | 63 +- source/mir/util/HTTPRequestParser.java | 6 +- source/mir/util/InternetFunctions.java | 18 +- source/mir/util/JDBCStringRoutines.java | 5 +- source/mir/util/ParameterExpander.java | 105 +- source/mir/util/PropertiesManipulator.java | 1 - source/mir/util/ReflectionRoutines.java | 60 + .../mir/util/ResourceBundleGeneratorFunction.java | 93 - source/mir/util/StreamCopier.java | 49 + source/mir/util/StringParseRoutines.java | 75 +- source/mir/util/StringRoutines.java | 641 +++-- source/mir/util/StructuredContentParser.java | 16 +- source/mir/util/XMLReader.java | 365 --- .../BundleGeneratorFunction.java} | 71 +- .../ReflectionGeneratorFunctionAdapter.java} | 134 +- .../ReflectionGeneratorFunctionsAdapter.java | 53 + source/mir/util/xml/AbstractSectionHandler.java | 39 + source/mir/util/xml/SectionHandler.java | 51 + source/mir/util/xml/XMLName.java | 88 + source/mir/util/xml/XMLParserEngine.java | 280 ++ source/mir/util/xml/XMLParserExc.java | 34 + source/mir/util/xml/XMLParserFailure.java | 20 + source/mir/util/{ => xml}/XMLReaderTool.java | 106 +- source/mir/util/xml/XMLSAXParserProvider.java | 160 ++ source/mir/util/xml/html/HTMLParser.java | 154 + source/mir/util/xml/html/HTMLParserExc.java | 34 + source/mir/util/xml/html/HTMLParserFailure.java | 20 + source/mir/util/xml/html/HTMLScanner.java | 310 +++ .../mir/util/xml/html/HTMLSchemaInformation.java | 170 ++ .../mir/util/xml/html/XMLHTMLParserProvider.java | 96 + 142 files changed, 11043 insertions(+), 6446 deletions(-) create mode 100755 source/mir/bundle/BasicBundleFactory.java rename source/mir/{misc/HTMLParseException.java => bundle/Bundle.java} (79%) create mode 100755 source/mir/bundle/BundleFactory.java create mode 100755 source/mir/bundle/BundleLoader.java create mode 100755 source/mir/bundle/CascadingBundleFactory.java rename source/mir/{media/MediaHelper.java => bundle/PropertiesBundle.java} (50%) create mode 100755 source/mir/bundle/PropertiesFileBundleLoader.java create mode 100755 source/mir/entity/AbstractEntity.java create mode 100755 source/mir/generator/GeneratorHelper.java create mode 100755 source/mir/generator/TALGenerator.java create mode 100755 source/mir/generator/VelocityGenerator.java create mode 100755 source/mir/generator/tal/CachingFileLoader.java create mode 100755 source/mir/generator/tal/MirExpressionParser.java rename source/mir/{producer/NodedProducerFactory.java => generator/tal/SimpleTemplateNodeLibraryRegistry.java} (57%) create mode 100755 source/mir/generator/tal/TALExc.java create mode 100755 source/mir/generator/tal/TALFailure.java create mode 100755 source/mir/generator/tal/TALTemplateEngine.java create mode 100755 source/mir/generator/tal/TALTemplateParser.java create mode 100755 source/mir/generator/tal/TALTest.java create mode 100755 source/mir/generator/tal/interfaces/TALExpressionParser.java create mode 100755 source/mir/generator/tal/interfaces/TALLogger.java create mode 100755 source/mir/generator/tal/template/CompositeTemplateNode.java create mode 100755 source/mir/generator/tal/template/CoreTemplateNodeLibrary.java create mode 100755 source/mir/generator/tal/template/MacroTemplateNodeLibrary.java create mode 100755 source/mir/generator/tal/template/PlainTextTemplateNode.java create mode 100755 source/mir/generator/tal/template/Template.java create mode 100755 source/mir/generator/tal/template/TemplateLibrary.java create mode 100755 source/mir/generator/tal/template/TemplateNode.java create mode 100755 source/mir/generator/tal/template/TemplateNodeLibrary.java create mode 100755 source/mir/generator/tal/template/TemplateNodeLibraryRegistry.java create mode 100755 source/mir/generator/tal/template/TemplateProcessingException.java rename source/mir/log/{Log.java => LoggerEngine.java} (73%) rename source/mir/log/{TestFramework.java => LoggerExc.java} (80%) create mode 100755 source/mir/log/LoggerFailure.java rename source/mir/media/{MirMedia.java => MediaHandler.java} (68%) delete mode 100755 source/mir/misc/LineFilterWriter.java rename source/mir/producer/{ResourceBundleProducerNode.java => BundleProducerNode.java} (60%) create mode 100755 source/mir/producer/ExecuteProgramProducerNode.java create mode 100755 source/mir/producer/ExternalDbProducerNode.java delete mode 100755 source/mir/rss/RSSTest.java rename source/mir/{producer/ScriptCallingProducerNode.java => util/EntityUtility.java} (59%) delete mode 100755 source/mir/util/GeneratorHTMLFunctions.java delete mode 100755 source/mir/util/GeneratorIntegerFunctions.java delete mode 100755 source/mir/util/GeneratorListFunctions.java delete mode 100755 source/mir/util/GeneratorStringFunctions.java create mode 100755 source/mir/util/HTTPClientHelper.java create mode 100755 source/mir/util/ReflectionRoutines.java delete mode 100755 source/mir/util/ResourceBundleGeneratorFunction.java create mode 100755 source/mir/util/StreamCopier.java delete mode 100755 source/mir/util/XMLReader.java rename source/mir/util/{GeneratorExpressionFunctions.java => generator/BundleGeneratorFunction.java} (56%) rename source/mir/util/{GeneratorRegularExpressionFunctions.java => generator/ReflectionGeneratorFunctionAdapter.java} (54%) create mode 100755 source/mir/util/generator/ReflectionGeneratorFunctionsAdapter.java create mode 100755 source/mir/util/xml/AbstractSectionHandler.java create mode 100755 source/mir/util/xml/SectionHandler.java create mode 100755 source/mir/util/xml/XMLName.java create mode 100755 source/mir/util/xml/XMLParserEngine.java create mode 100755 source/mir/util/xml/XMLParserExc.java create mode 100755 source/mir/util/xml/XMLParserFailure.java rename source/mir/util/{ => xml}/XMLReaderTool.java (52%) create mode 100755 source/mir/util/xml/XMLSAXParserProvider.java create mode 100755 source/mir/util/xml/html/HTMLParser.java create mode 100755 source/mir/util/xml/html/HTMLParserExc.java create mode 100755 source/mir/util/xml/html/HTMLParserFailure.java create mode 100755 source/mir/util/xml/html/HTMLScanner.java create mode 100755 source/mir/util/xml/html/HTMLSchemaInformation.java create mode 100755 source/mir/util/xml/html/XMLHTMLParserProvider.java diff --git a/source/mir/bundle/BasicBundleFactory.java b/source/mir/bundle/BasicBundleFactory.java new file mode 100755 index 00000000..ac9aeb9d --- /dev/null +++ b/source/mir/bundle/BasicBundleFactory.java @@ -0,0 +1,86 @@ +/* + * 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.bundle; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * The BasicBundleFactory is responsible for managing + * loaded bundles. It caches previously retrieved bundles to improve + * performance. + */ +public class BasicBundleFactory implements BundleFactory { + private Map directories; + private BundleLoader loader; + + public BasicBundleFactory(BundleLoader aLoader) { + directories = new HashMap(); + loader = aLoader; + } + + private Map getBundleDirectory(String aDirectory) { + synchronized (directories) { + Map result = (Map) directories.get(aDirectory); + + if (result == null) { + result = new HashMap(); + directories.put(aDirectory, result); + } + + return result; + } + } + + private Bundle loadBundle(String aDirectory, String[] aParameters) { + return loader.loadBundle(aDirectory, aParameters); + } + + public Bundle getBundle(String aDirectory, String[] aParameters) { + Map directory = getBundleDirectory(aDirectory); + List parameters = java.util.Arrays.asList(aParameters); + + Bundle result = (Bundle) directory.get(parameters); + + if (result==null) { + result = loadBundle(aDirectory, aParameters); + directory.put(parameters, result); + } + + return result; + } + + public void reload() { + synchronized (directories) { + directories.clear(); + } + } +} diff --git a/source/mir/misc/HTMLParseException.java b/source/mir/bundle/Bundle.java similarity index 79% rename from source/mir/misc/HTMLParseException.java rename to source/mir/bundle/Bundle.java index 3e139564..cec44e49 100755 --- a/source/mir/misc/HTMLParseException.java +++ b/source/mir/bundle/Bundle.java @@ -18,31 +18,19 @@ * 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. + * 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; +package mir.bundle; +import java.util.List; -/* - * HTMLParseException - - * wird vom HTMLProcessor geschmissen - * - * - * @version 30.6.199 - * @author RK - */ - -public class HTMLParseException extends Exception -{ - HTMLParseException(String msg) { - super(msg); - } +public interface Bundle { + public String getValue(String aKey, List anArguments); } - diff --git a/source/mir/bundle/BundleFactory.java b/source/mir/bundle/BundleFactory.java new file mode 100755 index 00000000..7df1476b --- /dev/null +++ b/source/mir/bundle/BundleFactory.java @@ -0,0 +1,42 @@ +/* + * 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.bundle; + +public interface BundleFactory { + /** + * Retrieves a bundle + */ + public Bundle getBundle(String aDirectory, String[] aParameters); + + /** + * Invalidates the bundle cache + */ + public void reload(); +} diff --git a/source/mir/bundle/BundleLoader.java b/source/mir/bundle/BundleLoader.java new file mode 100755 index 00000000..7674e94c --- /dev/null +++ b/source/mir/bundle/BundleLoader.java @@ -0,0 +1,52 @@ +/* + * 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.bundle; + +/** + *

+ * The BundleLoader is responsible for the physical loading of (abstract) + * {@link Bundle}s. A Bundle is identified by a directory + * and a set of parameters. The directory typically denotes the base of + * a set of Bundles, the parameters stand for a particular + * instance. E.g. the directory might stand for the purpose of the bundles, + * the parameters for the locale. + *

+ *

+ * BundleLoaders should not do any caching, since that's the + * responsibility of the {@link BasicBundleFactory}. + *

+ */ +public interface BundleLoader { + /** + * Loads the bundle specified by aDirectory and + * aParameters. + */ + public Bundle loadBundle(String aDirectory, String[] aParameters); +} diff --git a/source/mir/bundle/CascadingBundleFactory.java b/source/mir/bundle/CascadingBundleFactory.java new file mode 100755 index 00000000..b3a9920e --- /dev/null +++ b/source/mir/bundle/CascadingBundleFactory.java @@ -0,0 +1,70 @@ +/* + * 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.bundle; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class CascadingBundleFactory implements BundleFactory { + private BundleFactory masterFactory; + + /** {@inheritDoc} */ + public CascadingBundleFactory(BundleFactory aMasterFactory) { + masterFactory = aMasterFactory; + } + + /** {@inheritDoc} */ + public Bundle getBundle(final String aDirectory, final String[] aParameters) { + return + new Bundle() { + public String getValue(String aKey, List anArguments) { + String result = masterFactory.getBundle(aDirectory, aParameters).getValue(aKey, anArguments); + + if (aParameters.length>0 && result==null) { + List parameters = new ArrayList(Arrays.asList(aParameters)); + + while (result==null && parameters.size()>0) { + parameters.remove(parameters.size()-1); + result = masterFactory.getBundle( + aDirectory, (String[]) parameters.toArray(new String[0])).getValue(aKey, anArguments); + } + } + + return result; + } + }; + } + + /** {@inheritDoc} */ + public void reload() { + masterFactory.reload(); + } +} diff --git a/source/mir/media/MediaHelper.java b/source/mir/bundle/PropertiesBundle.java similarity index 50% rename from source/mir/media/MediaHelper.java rename to source/mir/bundle/PropertiesBundle.java index a4d43779..a7952852 100755 --- a/source/mir/media/MediaHelper.java +++ b/source/mir/bundle/PropertiesBundle.java @@ -18,62 +18,67 @@ * 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. + * 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; +package mir.bundle; -import java.lang.reflect.Method; - -import mir.entity.Entity; -import mir.storage.Database; +import java.util.Properties; +import java.util.List; +import java.util.Iterator; +import mir.util.StringParseRoutines; /** - * helper class to resolve media handlers using reflection - * - * @author mh - * @version 2002 + * Bundle implementation using a {@link Properties} + * object. */ -public final class MediaHelper { +public class PropertiesBundle implements Bundle { + private Properties properties; + + public PropertiesBundle(Properties aProperties) { + properties = aProperties; + } - static String _classPrefix = "mircoders.media.MediaHandler"; + private String formatValue(String anExpression, List anArguments) { + StringBuffer result = new StringBuffer(); - public static MirMedia getHandler( Entity mediaType ) throws MediaExc, MediaFailure { + List parts = StringParseRoutines.parseBracketedExpression( + anExpression, '\\', "{", "}" ); - MirMedia mediaHandler; - String handlerName = mediaType.getValue("classname"); - try { - Class handlerClass = Class.forName(_classPrefix+handlerName); - return mediaHandler = (MirMedia)handlerClass.newInstance(); - } - catch (Throwable e) { - throw new MediaFailure("getHandler -- error in reflection " + e.toString(), e); + Iterator i = parts.iterator(); + while (i.hasNext()) { + result.append(i.next()); + if (i.hasNext()) { + String expression = (String) i.next(); + try { + int parameterNr = Integer.parseInt(expression); + if (parameterNr>=0 && parameterNrWEB-INF dir of the + * deployed mir servlets. */ - public String getStringWithHome(String key) { - String returnString = getString(key); - - if (returnString == null) { - returnString = new String(); - } - - return getString("Home") + returnString; + public File getHome() { + return home; } /** - * Checks if one property is missing and adds a default value + * Returns a file based on a configuration setting. + * + * The file may be configured with an absolute path, or + * it may be a relative path. + * + * Relative paths work relative to {@link #home} : + * normally this is the WEB-INF dir in a + * deployed java servlet. */ - private void checkMissing() { - for (int i = 0; i < neededWithValue.length; i++) { - if (super.getProperty(neededWithValue[i].getKey()) == null) { - addProperty(neededWithValue[i].getKey(), neededWithValue[i].getValue()); - } - } - } + public File getFile(String aKey) { + String path = getString(aKey); - public File getFile(String key) throws FileNotFoundException { - String path = getStringWithHome(key); - File returnFile = new File(path); - - if (returnFile.exists()) { - return returnFile; - } else { - throw new FileNotFoundException(); + File result = new File(path); + if (result.isAbsolute()) { + return result; + } + else { + return new File(home, path); } } /** * @return the vlaue of this property as String * @param key the key of this property - * @see org.apache.commons.configuration.Configuration#getString(java.lang.String) */ public String getString(String key) { return getString(key, ""); @@ -204,11 +183,26 @@ public class MirPropertiesConfiguration extends ExtendedProperties { return object.toString(); } + public boolean getBoolean(String aKey, boolean aDefaultValue) { + try { + return getBoolean(aKey); + } + catch (Throwable t) { + return aDefaultValue; + } + } + + public boolean getBoolean(String aKey) { + String value = getString(aKey).trim(); + + return "1".equals(value) || "y".equalsIgnoreCase(value) || + "yes".equalsIgnoreCase(value) || "true".equalsIgnoreCase(value); + } + /** * Returns a property according to the given key * @param key the key of the property * @return the value of the property as Object, if no property available it returns a empty String - * @see org.apache.commons.configuration.Configuration#getString(java.lang.String) */ public Object getProperty(String key) { if (super.getProperty(key) == null) { @@ -224,7 +218,6 @@ public class MirPropertiesConfiguration extends ExtendedProperties { public static class PropertiesConfigExc extends Exc { /** * Constructor for PropertiesConfigExc. - * @param arg0 */ public PropertiesConfigExc(String msg) { super(msg); @@ -237,32 +230,9 @@ public class MirPropertiesConfiguration extends ExtendedProperties { public static class PropertiesConfigFailure extends Failure { /** * Constructor for PropertiesConfigExc. - * @param arg0 */ public PropertiesConfigFailure(String msg, Throwable cause) { super(msg, cause); } } - - /** - * A Class for properties to be checked - * @author idefix - */ - private static class NeededProperty { - private String _key; - private String _value; - - public NeededProperty(String key, String value) { - _key = key; - _value = value; - } - - public String getKey() { - return _key; - } - - public String getValue() { - return _value; - } - } } diff --git a/source/mir/entity/AbstractEntity.java b/source/mir/entity/AbstractEntity.java new file mode 100755 index 00000000..ec6d9b0a --- /dev/null +++ b/source/mir/entity/AbstractEntity.java @@ -0,0 +1,164 @@ +/* + * 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.entity; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import mir.config.MirPropertiesConfiguration; +import mir.config.MirPropertiesConfiguration.PropertiesConfigExc; +import mir.log.LoggerWrapper; +import mir.storage.StorageObject; +import mir.storage.StorageObjectExc; +import mir.storage.StorageObjectFailure; + +/** + * Base class the entities are derived from. Provides base functionality of + * an entity. + * + * @version $Id: AbstractEntity.java,v 1.9 2004/11/06 19:18:12 idfx Exp $ + */ + +public class AbstractEntity implements Entity { + protected static MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance(); + + protected Map values; + protected StorageObject storageObject; + protected LoggerWrapper logger; + + public AbstractEntity() { + logger = new LoggerWrapper("Entity"); + + values = new HashMap(); + } + + /** + * Constructor + * @param StorageObject The StorageObject of the Entity. + */ + public AbstractEntity(StorageObject StorageObject) { + this(); + + setStorage(StorageObject); + } + + public void setStorage(StorageObject storage) { + this.storageObject = storage; + } + + /** {@inheritDoc} */ + public void setFieldValues(Map aMap) { + if (aMap!=null) { + Iterator i = aMap.entrySet().iterator(); + synchronized(this) { + while (i.hasNext()) { + Map.Entry entry = (Map.Entry) i.next(); + + setFieldValue( (String) entry.getKey(), (String) entry.getValue()); + } + } + } + } + + /** {@inheritDoc} */ + public String getId() { + return getFieldValue(storageObject.getIdName()); + } + + /** {@inheritDoc} */ + public void setId(String id) { + setFieldValue(storageObject.getIdName(), id); + } + + /** {@inheritDoc} */ + public String insert() throws StorageObjectExc { + logger.debug("Entity: trying to insert ..."); + + if (storageObject != null) { + return storageObject.insert(this); + } + else + throw new StorageObjectExc("storageObject == null!"); + } + + /** {@inheritDoc} */ + public void update() throws StorageObjectFailure { + storageObject.update(this); + } + + /** {@inheritDoc} */ + public String getFieldValue(String aFieldName) { + String returnValue = null; + + if (aFieldName != null) { + returnValue = (String) values.get(aFieldName); + } + return returnValue; + } + + /** {@inheritDoc} */ + public boolean hasFieldValue(String aFieldName) { + return values.containsKey(aFieldName); + } + + /** + * Sets the value for a field. Issues a log message if the field name + * supplied was not found in the Entity. + * @param theProp The field name whose value has to be set + * @param theValue The new value of the field + * @exception StorageObjectFailure + */ + public void setFieldValue(String theProp, String theValue) throws StorageObjectFailure { + if (hasField(theProp)) + values.put(theProp, theValue); + else { + logger.warn("Entity.setFieldValue: Property not found: " + theProp + " (" + theValue + ")"); + } + } + + /** + * Returns the field names of the Entity + */ + public List getFieldNames() throws StorageObjectFailure { + return storageObject.getFields(); + } + + /** Returns whether fieldName is a valid field name of this Entity. + * @param fieldName + * @return true in case fieldName is a field name, else false. + * @exception StorageObjectFailure + */ + public boolean hasField(String fieldName) throws StorageObjectFailure { + return getFieldNames().contains(fieldName); + } +} + diff --git a/source/mir/entity/Entity.java b/source/mir/entity/Entity.java index 30823c04..6a66881b 100755 --- a/source/mir/entity/Entity.java +++ b/source/mir/entity/Entity.java @@ -30,70 +30,27 @@ package mir.entity; import java.util.HashMap; +import java.util.Iterator; import java.util.List; -import java.util.*; +import java.util.Map; import mir.config.MirPropertiesConfiguration; import mir.config.MirPropertiesConfiguration.PropertiesConfigExc; import mir.log.LoggerWrapper; -import mir.misc.StringUtil; import mir.storage.StorageObject; import mir.storage.StorageObjectExc; import mir.storage.StorageObjectFailure; /** - * Base class the entities are derived from. Provides base functionality of - * an entity. Entities are used to represent rows of a database table.

- * - * @version $Id: Entity.java,v 1.22 2003/09/03 18:29:01 zapata Exp $ - * @author rk + * An Entity represents a persistent data object, typically + * stored in a database.

* + * @version $Id: Entity.java,v 1.23 2004/11/06 19:18:12 idfx Exp $ */ -public class Entity +public interface Entity { - protected static MirPropertiesConfiguration configuration; - -// protected Map theValuesHash; // tablekey / value - protected Map values; - protected StorageObject theStorageObject; - protected List streamedInput = null; - protected LoggerWrapper logger; - - static { - try { - configuration = MirPropertiesConfiguration.instance(); - } - catch (PropertiesConfigExc e) { - throw new RuntimeException(e.getMessage()); - } - } - - public Entity() { - logger = new LoggerWrapper("Entity"); - - values = new HashMap(); - } - - /** - * Constructor - * @param StorageObject The StorageObject of the Entity. - */ - - public Entity(StorageObject StorageObject) { - this(); - - setStorage(StorageObject); - } - - /** - * - * @param storage - */ - - public void setStorage(StorageObject storage) { - this.theStorageObject = storage; - } + public void setStorage(StorageObject storage); /** * Sets the values of the Entity. (Only to be called by the Storage Object) @@ -101,157 +58,58 @@ public class Entity * @param aMap Map containing the new values of the Entity */ - public void setValues(Map aMap) { - if (aMap!=null) { - Iterator i = aMap.entrySet().iterator(); - synchronized(this) { - while (i.hasNext()) { - Map.Entry entry = (Map.Entry) i.next(); - - setValueForProperty( (String) entry.getKey(), (String) entry.getValue()); - } - } - } - } + public void setFieldValues(Map aMap); /** * Returns the primary key of the Entity. * @return String Id */ - public String getId() { - return (String) getValue(theStorageObject.getIdName()); - } + public String getId(); /** * Defines the primary key of the Entity (only to be set by the StorageObject) * @param id */ - public void setId(String id) { - setValueForProperty(theStorageObject.getIdName(), id); - } - - /** - * Returns the value of a field by field name. - * @param field The name of the field - * @return value of the field - */ - public String getValue(String field) { - String returnValue = null; - - if (field != null) { - returnValue = (String) values.get(field); - } - return returnValue; - } - - public boolean hasValueForField(String field) { - return values.containsKey(field); - } + public void setId(String id); /** * Insers Entity into the database via StorageObject * @return Primary Key of the Entity - * @exception StorageObjectException + * @exception StorageObjectExc */ - public String insert() throws StorageObjectExc { - logger.debug("Entity: trying to insert ..."); - - if (theStorageObject != null) { - return theStorageObject.insert(this); - } - else - throw new StorageObjectExc("theStorageObject == null!"); - } + public String insert() throws StorageObjectExc; /** * Saves changes of this Entity to the database - * @exception StorageObjectException + * @exception StorageObjectFailure */ - public void update() throws StorageObjectFailure { - theStorageObject.update(this); - } + public void update() throws StorageObjectFailure; /** * Sets the value for a field. Issues a log message if the field name * supplied was not found in the Entity. * @param theProp The field name whose value has to be set * @param theValue The new value of the field - * @exception StorageObjectException + * @exception StorageObjectFailure */ - public void setValueForProperty(String theProp, String theValue) throws StorageObjectFailure { - try { - if (isField(theProp)) - values.put(theProp, theValue); - else { - logger.warn("Entity.setValueForProperty: Property not found: " + theProp + " (" + theValue + ")"); - } - } - catch (Throwable t) { - logger.error("Entity.setValueForProperty: " + t.toString()); - t.printStackTrace(logger.asPrintWriter(logger.DEBUG_MESSAGE)); - - throw new StorageObjectFailure(t); - } - } + public void setFieldValue(String theProp, String theValue); /** - * Returns the field names of the Entity as ArrayListe. - * @return ArrayList with field names - * @exception StorageObjectException is throuwn if database access was impossible + * Returns the field names of the Entity */ - public List getFields() throws StorageObjectFailure { - return theStorageObject.getFields(); - } + public List getFieldNames() throws StorageObjectFailure; /** - * Returns an int[] with the types of the fields - * @return int[] that contains the types of the fields - * @exception StorageObjectException - */ - public int[] getTypes() throws StorageObjectFailure { - return theStorageObject.getTypes(); - } - - /** - * Returns an ArrayList with field names - * @return List with field names - * @exception StorageObjectException - */ - public List getLabels() throws StorageObjectFailure { - return theStorageObject.getLabels(); - } - - - /** - * Returns an ArrayList with all database fields that can - * be evaluated as streamedInput. - * Could be automated by the types (blob, etc.) - * Until now to be created manually in the inheriting class - * - * Liefert einen ArrayList mit allen Datenbankfeldern, die - * als streamedInput ausgelesen werden muessen. - * Waere automatisierbar ueber die types (blob, etc.) - * Bisher manuell anzulegen in der erbenden Klasse + * Returns the value of a field by field name. + * @param field The name of the field + * @return value of the field */ + public String getFieldValue(String field); - public List streamedInput() { - return streamedInput; - } + public boolean hasFieldValue(String field); /** Returns whether fieldName is a valid field name of this Entity. - * @param fieldName - * @return true in case fieldName is a field name, else false. - * @exception StorageObjectException */ - public boolean isField(String fieldName) throws StorageObjectFailure { - return theStorageObject.getFields().contains(fieldName); - } - - protected void throwStorageObjectFailure(Throwable e, String wo) throws StorageObjectFailure { - logger.error(e.toString() + " function: " + wo); - e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); - - throw new StorageObjectFailure("Storage Object Exception in entity", e); - } + public boolean hasField(String aFieldName) throws StorageObjectFailure; } diff --git a/source/mir/entity/EntityBrowser.java b/source/mir/entity/EntityBrowser.java index 44b21f4a..77bc5593 100755 --- a/source/mir/entity/EntityBrowser.java +++ b/source/mir/entity/EntityBrowser.java @@ -18,18 +18,20 @@ * 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. + * 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.entity; +import java.util.List; + import mir.storage.StorageObject; import mir.storage.StorageObjectFailure; import mir.util.RewindableIterator; @@ -37,10 +39,11 @@ import mir.util.RewindableIterator; public class EntityBrowser implements RewindableIterator { private StorageObject storage; + private String mainTablePrefix; + private List extraTables; private String whereClause; private String orderByClause; private int batchSize; - private int toFetch; private EntityList currentBatch; private int skip; @@ -49,10 +52,13 @@ public class EntityBrowser implements RewindableIterator { private int batchPosition; private int positionInBatch; - public EntityBrowser(StorageObject aStorage, String aWhereClause, String anOrderByClause, - int aBatchSize, int aLimit, int aSkip) throws StorageObjectFailure { + public EntityBrowser(StorageObject aStorage, String aMainTablePrefix, List someExtraTables, + String aWhereClause, String anOrderByClause, + int aBatchSize, int aLimit, int aSkip) throws StorageObjectFailure { storage=aStorage; + mainTablePrefix=aMainTablePrefix; + extraTables=someExtraTables; whereClause=aWhereClause; orderByClause=anOrderByClause; batchSize=aBatchSize; @@ -62,6 +68,11 @@ public class EntityBrowser implements RewindableIterator { rewind(); } + public EntityBrowser(StorageObject aStorage, String aWhereClause, String anOrderByClause, + int aBatchSize, int aLimit, int aSkip) throws StorageObjectFailure { + this(aStorage, "", null, aWhereClause, anOrderByClause, aBatchSize, aLimit, aSkip); + } + public EntityBrowser(StorageObject aStorage, String aWhereClause, String anOrderByClause, int aBatchSize) throws StorageObjectFailure { @@ -69,7 +80,7 @@ public class EntityBrowser implements RewindableIterator { } public void readCurrentBatch(int aSkip) throws StorageObjectFailure { - currentBatch = storage.selectByWhereClause(whereClause, orderByClause, aSkip, batchSize); + currentBatch = storage.selectByWhereClause(mainTablePrefix, extraTables, whereClause, orderByClause, aSkip, batchSize); batchPosition = aSkip; positionInBatch = 0; } diff --git a/source/mir/entity/EntityList.java b/source/mir/entity/EntityList.java index f7924137..e9c839a0 100755 --- a/source/mir/entity/EntityList.java +++ b/source/mir/entity/EntityList.java @@ -1,267 +1,254 @@ -/* - * 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.entity; - -import java.util.ArrayList; -import java.util.Set; - -import mir.config.MirPropertiesConfiguration; -import mir.config.MirPropertiesConfiguration.PropertiesConfigExc; -import mir.log.LoggerWrapper; -import mir.storage.StorageObject; -import mir.storage.store.StorableObject; -import mir.storage.store.StoreContainerType; -import mir.storage.store.StoreIdentifier; -import mir.storage.store.StoreUtil; - -/** - * - * Container class for lists of Entities. - * Now implements @see mir.storage.store.StorableObject. - * - * @author - * first version 27.6.1999 - * - * @version 1.1 (cleaned up) - */ -public class EntityList implements StorableObject { - protected static MirPropertiesConfiguration configuration; - protected LoggerWrapper logger; - private ArrayList theEntityArrayList = new ArrayList(); - private String whereClause, orderClause; - private StorageObject theStorage; - private int count, offset, limit; - private int offsetnext = -1, offsetprev = -1; - - static { - try { - configuration = MirPropertiesConfiguration.instance(); - } - catch (PropertiesConfigExc e) { - throw new RuntimeException("Unable to get configuration: " + e.getMessage()); - } - } - - /** - * Constructor. - */ - public EntityList(){ - logger = new LoggerWrapper("Entity.List"); - } - -/* get/set EntityClass of Objects stored in EntityList */ - public void setStorage(StorageObject storage) { this.theStorage=storage; } - public StorageObject getStorage() { return theStorage; } - - public void setLimit(int limit) { this.limit = limit; } - - /** - * Sets the WHERE clause that fetched the Entities of this EntityList from the database. - * @param wc The string that contains the WHERE clause - */ - public void setWhere(String wc) { - this.whereClause = wc; - } - - /** - * 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 - */ - public void setOrder(String oc) { - this.orderClause = oc; - } - - /** - * Returns the sorting criterium. - * @return orderClause The sort order - */ - public String getOrder() { - return orderClause; - } - - /** - * Sets the number of rows that match the WHERE clause - * @param i The number of rows that match the WHERE clause - */ - public void setCount(int i) { - this.count = i; - } - - /** - * Returns the number of rows that match the WHERE clause - * @return The number of rows ... - */ - public int getCount() { - return count; - } - - /** - * Sets the offset - * @param i The offset - */ - public void setOffset(int i) { - offset = i; - } - - /** - * Returns the offset - * @return offset - */ - public int getOffset() { - return offset; - } - - /** - * Sets the offset of the next batch of Entities. - * @param i The next offset - */ - public void setNextBatch(int i) { - offsetnext = i; - } - - /** - * Returns the offset of the next batch of Entities. - * @return offset of the next batch - */ - public int getNextBatch() { - return offsetnext; - } - - /** - * Returns whether there is a next batch within the WHERE clause - * @return true if yes, false if no. - */ - public boolean hasNextBatch() { - return (offsetnext >= 0); - } - - /** - * Sets the offset of the previous batch. - * @param i the previous offset - */ - public void setPrevBatch(int i) { - offsetprev = i; - } - - /** - * Returns the offset of the previous batch. - * @return offset of the previous batch - */ - public int getPrevBatch() { - return offsetprev; - } - - /** - * Returns whether there is a previous batch. - * @return true if yes, false if no - */ - public boolean hasPrevBatch() { - return (offsetprev >= 0); - } - - /** - * Returns the start index of the batch. - * @return - */ - public int getFrom() { - return offset+1; - } - - /** - * Returns the end index of the batch. - * @return - */ - public int getTo() { - if (hasNextBatch()) - return offsetnext; - else - return count; - } - - /** - * Inserts an Entity into the EntityList. - * @param anEntity The entity to be inserted. - */ - - public void add (Entity anEntity) { - if (anEntity!=null) - theEntityArrayList.add(anEntity); - else - logger.warn("EntityList: add called with empty Entity"); - } - - - /** - * @return The number of Entities in the EntityList. - */ - - public int size() { - return theEntityArrayList.size(); - } - - - /** - * Returns the element at position i in the EntityList as Entity - * @param i the position of the element in question - * @return The element at position i. - */ - - public Entity elementAt(int i) { - /** @todo check if i is in list.size() */ - return (Entity)theEntityArrayList.get(i); - } - - - -// Methods to implement StorableObject - - public Set getNotifyOnReleaseSet() { return null; } - - public StoreIdentifier getStoreIdentifier() { - if ( theStorage!=null ) { - return - new StoreIdentifier( this, StoreContainerType.STOC_TYPE_ENTITYLIST, - StoreUtil.getEntityListUniqueIdentifierFor( theStorage.getTableName(), - whereClause, orderClause, offset, limit )); - } - logger.warn("EntityList could not return StoreIdentifier"); - return null; - } - -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, but you are not obligated to do so. + * If you do not wish to do so, delete this exception statement from your version. + */ +package mir.entity; + +import java.util.ArrayList; +import java.util.Set; + +import mir.config.MirPropertiesConfiguration; +import mir.config.MirPropertiesConfiguration.PropertiesConfigExc; +import mir.log.LoggerWrapper; +import mir.storage.StorageObject; +import mir.storage.store.StorableObject; +import mir.storage.store.StoreContainerType; +import mir.storage.store.StoreIdentifier; +import mir.storage.store.StoreUtil; + +/** + * + * Container class for lists of Entities. + * Now implements @see mir.storage.store.StorableObject. + * + * @author + * first version 27.6.1999 + * + * @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 String whereClause, orderClause; + private StorageObject theStorage; + private int count, offset, limit; + private int offsetnext = -1, offsetprev = -1; + + public EntityList(){ + logger = new LoggerWrapper("Entity.List"); + } + +/* get/set EntityClass of Objects stored in EntityList */ + public void setStorage(StorageObject storage) { this.theStorage=storage; } + public StorageObject getStorage() { return theStorage; } + + public void setLimit(int limit) { this.limit = limit; } + + /** + * Sets the WHERE clause that fetched the Entities of this EntityList from the database. + * @param wc The string that contains the WHERE clause + */ + public void setWhere(String wc) { + this.whereClause = wc; + } + + /** + * 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 + */ + public void setOrder(String oc) { + this.orderClause = oc; + } + + /** + * Returns the sorting criterium. + * @return orderClause The sort order + */ + public String getOrder() { + return orderClause; + } + + /** + * Sets the number of rows that match the WHERE clause + * @param i The number of rows that match the WHERE clause + */ + public void setCount(int i) { + this.count = i; + } + + /** + * Returns the number of rows that match the WHERE clause + * @return The number of rows ... + */ + public int getCount() { + return count; + } + + /** + * Sets the offset + * @param i The offset + */ + public void setOffset(int i) { + offset = i; + } + + /** + * Returns the offset + * @return offset + */ + public int getOffset() { + return offset; + } + + /** + * Sets the offset of the next batch of Entities. + * @param i The next offset + */ + public void setNextBatch(int i) { + offsetnext = i; + } + + /** + * Returns the offset of the next batch of Entities. + * @return offset of the next batch + */ + public int getNextBatch() { + return offsetnext; + } + + /** + * Returns whether there is a next batch within the WHERE clause + * @return true if yes, false if no. + */ + public boolean hasNextBatch() { + return (offsetnext >= 0); + } + + /** + * Sets the offset of the previous batch. + * @param i the previous offset + */ + public void setPrevBatch(int i) { + offsetprev = i; + } + + /** + * Returns the offset of the previous batch. + * @return offset of the previous batch + */ + public int getPrevBatch() { + return offsetprev; + } + + /** + * Returns whether there is a previous batch. + * @return true if yes, false if no + */ + public boolean hasPrevBatch() { + return (offsetprev >= 0); + } + + /** + * Returns the start index of the batch. + * @return + */ + public int getFrom() { + return offset+1; + } + + /** + * Returns the end index of the batch. + * @return + */ + public int getTo() { + if (hasNextBatch()) + return offsetnext; + else + return count; + } + + /** + * Inserts an Entity into the EntityList. + * @param anEntity The entity to be inserted. + */ + + public void add (Entity anEntity) { + if (anEntity!=null) + theEntityArrayList.add(anEntity); + else + logger.warn("EntityList: add called with empty Entity"); + } + + + /** + * @return The number of Entities in the EntityList. + */ + + public int size() { + return theEntityArrayList.size(); + } + + + /** + * Returns the element at position i in the EntityList as Entity + * @param i the position of the element in question + * @return The element at position i. + */ + + public Entity elementAt(int i) { + /** todo check if i is in list.size() */ + return (Entity) theEntityArrayList.get(i); + } + + + +// Methods to implement StorableObject + + public Set getNotifyOnReleaseSet() { return null; } + + public StoreIdentifier getStoreIdentifier() { + if ( theStorage!=null ) { + return + new StoreIdentifier( this, StoreContainerType.STOC_TYPE_ENTITYLIST, + StoreUtil.getEntityListUniqueIdentifierFor( theStorage.getTableName(), + whereClause, orderClause, offset, limit )); + } + logger.warn("EntityList could not return StoreIdentifier"); + return null; + } + +} diff --git a/source/mir/entity/GenericEntity.java b/source/mir/entity/GenericEntity.java index d5632e1c..2a9f7b38 100755 --- a/source/mir/entity/GenericEntity.java +++ b/source/mir/entity/GenericEntity.java @@ -18,13 +18,13 @@ * 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. + * 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.entity; @@ -38,7 +38,7 @@ package mir.entity; * @author /rk * @version 1.2 */ -public class GenericEntity extends Entity {} +public class GenericEntity extends AbstractEntity {} diff --git a/source/mir/entity/StorableObjectEntity.java b/source/mir/entity/StorableObjectEntity.java index 79dc3bdc..b955d681 100755 --- a/source/mir/entity/StorableObjectEntity.java +++ b/source/mir/entity/StorableObjectEntity.java @@ -18,13 +18,13 @@ * 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. + * 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.entity; @@ -38,13 +38,16 @@ package mir.entity; * @version 1.0 */ +import java.sql.ResultSet; +import java.sql.SQLException; import java.util.Set; +import mir.storage.Database; import mir.storage.store.StorableObject; import mir.storage.store.StoreIdentifier; -public class StorableObjectEntity extends Entity +public class StorableObjectEntity extends AbstractEntity implements StorableObject { /** @@ -56,11 +59,34 @@ public class StorableObjectEntity extends Entity */ public StoreIdentifier getStoreIdentifier() { String id = getId(); - if ( id!=null && theStorageObject!= null ) - return new StoreIdentifier(this, id+"@"+theStorageObject.getTableName()); + if ( id!=null && storageObject!= null ) + return new StoreIdentifier(this, id+"@"+storageObject.getTableName()); return null; } + public static final StoreIdentifier getStoreIdentifier( + Class theEntityClass, String theTable, String id) { + if (id == null) { + return null; + } else { + return new StoreIdentifier(theEntityClass, id + "@" + theTable); + } + } + + public static final StoreIdentifier getStoreIdentifier(Database theStorage, + Class theEntityClass, ResultSet rs) throws SQLException { + + String idcol = theStorage.getIdName(); + String idval = rs.getObject(idcol).toString(); + + if (idval != null) { + return getStoreIdentifier(theEntityClass, + theStorage.getTableName(), idval); + } + + return null; + } + /** * Method: getNotifyOnReleaseSet() * Description: returns empty Set, GenericContainer does not implement diff --git a/source/mir/entity/adapter/EntityAdapter.java b/source/mir/entity/adapter/EntityAdapter.java index 42faf0ba..ee997e27 100755 --- a/source/mir/entity/adapter/EntityAdapter.java +++ b/source/mir/entity/adapter/EntityAdapter.java @@ -32,6 +32,7 @@ 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; @@ -54,9 +55,8 @@ public class EntityAdapter implements Map { public boolean containsKey(Object aKey) { try { if (aKey instanceof String) - return entity.hasValueForField((String) aKey) - || definition.hasCalculatedField((String) aKey) - || entity.getFields().contains(aKey); + return entity.hasField((String) aKey) + || definition.hasCalculatedField((String) aKey); } catch (Throwable t) { } @@ -94,7 +94,7 @@ public class EntityAdapter implements Map { return result; } else if (aKey instanceof String) { - return entity.getValue((String) aKey); + return entity.getFieldValue((String) aKey); } else { return null; @@ -141,6 +141,22 @@ public class EntityAdapter implements Map { throw new UnsupportedOperationException("EntityAdapter.entrySet()"); } + public Object getComplexRelation(String aMainTablePrefix, List someExtraTables, + String aWhereClause, String anOrderByClause, String aDefinition) { + try { + return + new CachingRewindableIterator( + new EntityIteratorAdapter(aMainTablePrefix, someExtraTables, + aWhereClause, anOrderByClause, + -1, getModel(), aDefinition, -1, 0) + ); + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + + public Object getRelation(String aWhereClause, String anOrderByClause, String aDefinition) { try { return @@ -155,7 +171,7 @@ public class EntityAdapter implements Map { public EntityAdapter getToOneRelation(String aWhereClause, String anOrderByClause, String aDefinition) { try { - Iterator i = new EntityIteratorAdapter(aWhereClause, anOrderByClause, -1, getModel(), aDefinition); + Iterator i = new EntityIteratorAdapter(aWhereClause, anOrderByClause, 1, getModel(), aDefinition, 1, 0); if (i.hasNext()) return (EntityAdapter) i.next(); @@ -166,4 +182,21 @@ public class EntityAdapter implements Map { throw new RuntimeException(t.getMessage()); } } + + public EntityAdapter getComplexToOneRelation(String aMainTablePrefix, List someExtraTables, + String aWhereClause, String anOrderByClause, String aDefinition) { + try { + Iterator i = new EntityIteratorAdapter(aMainTablePrefix, someExtraTables, aWhereClause, anOrderByClause, -1, + getModel(), aDefinition, 1, 0); + + if (i.hasNext()) + return (EntityAdapter) i.next(); + else + return null; + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + } \ No newline at end of file diff --git a/source/mir/entity/adapter/EntityAdapterDefinition.java b/source/mir/entity/adapter/EntityAdapterDefinition.java index 68cdf2f4..571df52e 100755 --- a/source/mir/entity/adapter/EntityAdapterDefinition.java +++ b/source/mir/entity/adapter/EntityAdapterDefinition.java @@ -29,17 +29,22 @@ */ package mir.entity.adapter; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.Map; -import java.util.TimeZone; - -import mir.entity.Entity; -import mir.misc.StringUtil; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.Map; +import java.util.TimeZone; + +import mir.entity.Entity; +import mir.misc.StringUtil; import mir.util.GeneratorFormatAdapters; +/** + * EntityAdapterDefinition defines the fields for an entity adapter of + * a particular "type". Custom calculated fields can be defined. + * + */ public class EntityAdapterDefinition { private Map calculatedFields; @@ -47,31 +52,76 @@ public class EntityAdapterDefinition { calculatedFields = new HashMap(); } + /** + * + * + * @param anEntity the entity that will be wrapped by the entity adapter + * @param aModel the base model + * @return the resulting entity adapter + */ public EntityAdapter makeEntityAdapter(Entity anEntity, EntityAdapterModel aModel) { return new EntityAdapter(anEntity, this, aModel); } + /** + * + * @param aFieldName + * @return the CalculatedField if it exists. null otherwise + */ public CalculatedField getCalculatedField(String aFieldName) { return (CalculatedField) calculatedFields.get(aFieldName); } + /** + * + * @param aFieldName + * @return + */ public boolean hasCalculatedField(String aFieldName) { return calculatedFields.containsKey(aFieldName); } + /** + * + * @param aFieldName + * @param aField + */ public void addCalculatedField(String aFieldName, CalculatedField aField) { calculatedFields.put(aFieldName, aField); } + /** + * To add a calculated field based on a "mir" date field: a string field of the form yyyyMMdd[hhmm] + * + * @param aDestinationFieldName + * @param aSourceFieldName + * @param aDefaultTimezone + */ public void addMirDateField(String aDestinationFieldName, String aSourceFieldName, String aDefaultTimezone) { addCalculatedField(aDestinationFieldName, new MirDateField(aSourceFieldName, aDefaultTimezone)); } + /** + * Adds a calculated field based on a db date field + * + * @param aDestinationFieldName the field name of the calculated field + * @param aSourceFieldName the field name of the entity (must be a date field) + * @param aDefaultTimezone the default timezone to use + */ public void addDBDateField(String aDestinationFieldName, String aSourceFieldName, String aDefaultTimezone) { addCalculatedField(aDestinationFieldName, new DBDateField(aSourceFieldName, aDefaultTimezone)); } + /** + * a calculated field: field gets its value from other fields. + */ public interface CalculatedField { + /** + * Method to retrieve the calculated value of the field. + * + * @param anEntityAdapter the entity + * @return the value of the field. + */ public Object getValue(EntityAdapter anEntityAdapter); } @@ -87,7 +137,7 @@ public class EntityAdapterDefinition { public Object getValue(EntityAdapter anEntityAdapter) { Object result = null; - String textValue = anEntityAdapter.getEntity().getValue(fieldName); + String textValue = anEntityAdapter.getEntity().getFieldValue(fieldName); Calendar calendar = GregorianCalendar.getInstance(); int year; int month; @@ -126,7 +176,7 @@ public class EntityAdapterDefinition { public Object getValue(EntityAdapter anEntityAdapter) { Object result = null; - String text = anEntityAdapter.getEntity().getValue(fieldName); + String text = anEntityAdapter.getEntity().getFieldValue(fieldName); if (text!=null) { try { diff --git a/source/mir/entity/adapter/EntityAdapterEngine.java b/source/mir/entity/adapter/EntityAdapterEngine.java index 4237c27f..2ef7c694 100755 --- a/source/mir/entity/adapter/EntityAdapterEngine.java +++ b/source/mir/entity/adapter/EntityAdapterEngine.java @@ -1,71 +1,71 @@ -/* - * 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.entity.adapter; - -import java.util.List; - -import mir.entity.EntityBrowser; -import mir.storage.*; - -/** - *

Title:

- *

Description:

- *

Copyright: Copyright (c) 2003

- *

Company:

- * @author not attributable - * @version 1.0 - */ - -public class EntityAdapterEngine { - private EntityAdapterEngine() { - } - - /** - * - * @param aStorage - * @param aDefinition - * @param aQualifier - * @param anOrder - * @param aLimit - * @param anOffset - * @return - */ - static public List retrieveAdapterList(EntityAdapterModel aModel, String aDefinition, String aQualifier, String anOrder, int aLimit, int anOffset) { - try { - EntityBrowser browser = new EntityBrowser(aModel.getMappingForName(aDefinition).getStorage(), aQualifier, anOrder, 30, aLimit, anOffset); - - return new EntityListAdapter(aModel, aDefinition, browser, aLimit); - } - catch (Throwable t) { - throw new StorageObjectFailure(t); - } - } +/* + * 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.entity.adapter; + +import java.util.List; + +import mir.entity.EntityBrowser; +import mir.storage.StorageObjectFailure; + +/** + *

Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ + +public class EntityAdapterEngine { + private EntityAdapterEngine() { + } + + /** + * + * @param aStorage + * @param aDefinition + * @param aQualifier + * @param anOrder + * @param aLimit + * @param anOffset + * @return + */ + static public List retrieveAdapterList(EntityAdapterModel aModel, String aDefinition, String aQualifier, String anOrder, int aLimit, int anOffset) { + try { + EntityBrowser browser = new EntityBrowser(aModel.getMappingForName(aDefinition).getStorage(), aQualifier, anOrder, 30, aLimit, anOffset); + + return new EntityListAdapter(aModel, aDefinition, browser, aLimit); + } + catch (Throwable t) { + throw new StorageObjectFailure(t); + } + } } \ No newline at end of file diff --git a/source/mir/entity/adapter/EntityIteratorAdapter.java b/source/mir/entity/adapter/EntityIteratorAdapter.java index 0b29d42c..dfa9ae7d 100755 --- a/source/mir/entity/adapter/EntityIteratorAdapter.java +++ b/source/mir/entity/adapter/EntityIteratorAdapter.java @@ -18,17 +18,19 @@ * 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. + * 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.entity.adapter; +import java.util.List; + import mir.entity.Entity; import mir.entity.EntityBrowser; import mir.storage.StorageObjectFailure; @@ -57,6 +59,14 @@ public class EntityIteratorAdapter implements RewindableIterator { this(new EntityBrowser(aModel.getMappingForName(aDefinitionName).getStorage(), aWhereClause, anOrderByClause, aBatchSize, aLimit, aSkip), aModel, aDefinitionName); } + public EntityIteratorAdapter(String aMainTablePrefix, List someExtraTables, + String aWhereClause, String anOrderByClause, + int aBatchSize, EntityAdapterModel aModel, String aDefinitionName, + int aLimit, int aSkip) throws StorageObjectFailure, EntityAdapterExc { + this(new EntityBrowser(aModel.getMappingForName(aDefinitionName).getStorage(), aMainTablePrefix, someExtraTables, aWhereClause, anOrderByClause, aBatchSize, aLimit, aSkip), aModel, aDefinitionName); + } + + public boolean hasNext() { return iterator.hasNext(); } diff --git a/source/mir/entity/adapter/EntityListAdapter.java b/source/mir/entity/adapter/EntityListAdapter.java index f7ae65de..19f37be7 100755 --- a/source/mir/entity/adapter/EntityListAdapter.java +++ b/source/mir/entity/adapter/EntityListAdapter.java @@ -1,122 +1,122 @@ -/* - * 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.entity.adapter; - -import java.util.AbstractList; -import java.util.List; -import java.util.Vector; - -import mir.entity.Entity; -import mir.entity.EntityBrowser; - -public class EntityListAdapter extends AbstractList { - private int skip; - private int maximumLength; - private EntityBrowser browser; - private EntityAdapterModel model; - private String definition; - private boolean exhausted = false; - private boolean skipped = false; - - private List cache; - - protected EntityListAdapter(EntityAdapterModel aModel, String aDefinition, EntityBrowser aBrowser, int aSkip, int aMaximumLength) { - model = aModel; - definition = aDefinition; - browser = aBrowser; - skip = aSkip; - maximumLength = aMaximumLength; - cache = new Vector(); - } - - protected EntityListAdapter(EntityAdapterModel aModel, String aDefinition, EntityBrowser aBrowser, int aMaximumLength) { - this(aModel, aDefinition, aBrowser, 0, aMaximumLength); - } - - protected EntityListAdapter(EntityAdapterModel aModel, String aDefinition, EntityBrowser aBrowser) { - this(aModel, aDefinition, aBrowser, 0, -1); - } - - private void skip() { - int i; - - try { - if (!skipped) { - for(i=0; i0 && cache.size()>=maximumLength) ; - } - } - catch (Throwable t) { - throw new RuntimeException(t.getMessage()); - } - - } - - private void exhaust() { - skip(); - - while (!exhausted) - fetchNext(); - } - - private void fetchUntil(int anIndex) { - skip(); - - while (!exhausted && anIndex>=cache.size()) - fetchNext(); - } - - public int size() { - exhaust(); - - return cache.size(); - } - - public Object get(int anIndex) { - fetchUntil(anIndex); - return cache.get(anIndex); - } +/* + * 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.entity.adapter; + +import java.util.AbstractList; +import java.util.ArrayList; +import java.util.List; + +import mir.entity.Entity; +import mir.entity.EntityBrowser; + +public class EntityListAdapter extends AbstractList { + private int skip; + private int maximumLength; + private EntityBrowser browser; + private EntityAdapterModel model; + private String definition; + private boolean exhausted = false; + private boolean skipped = false; + + private List cache; + + protected EntityListAdapter(EntityAdapterModel aModel, String aDefinition, EntityBrowser aBrowser, int aSkip, int aMaximumLength) { + model = aModel; + definition = aDefinition; + browser = aBrowser; + skip = aSkip; + maximumLength = aMaximumLength; + cache = new ArrayList(); + } + + protected EntityListAdapter(EntityAdapterModel aModel, String aDefinition, EntityBrowser aBrowser, int aMaximumLength) { + this(aModel, aDefinition, aBrowser, 0, aMaximumLength); + } + + protected EntityListAdapter(EntityAdapterModel aModel, String aDefinition, EntityBrowser aBrowser) { + this(aModel, aDefinition, aBrowser, 0, -1); + } + + private void skip() { + int i; + + try { + if (!skipped) { + for(i=0; i0 && cache.size()>=maximumLength) ; + } + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + + } + + private void exhaust() { + skip(); + + while (!exhausted) + fetchNext(); + } + + private void fetchUntil(int anIndex) { + skip(); + + while (!exhausted && anIndex>=cache.size()) + fetchNext(); + } + + public int size() { + exhaust(); + + return cache.size(); + } + + public Object get(int anIndex) { + fetchUntil(anIndex); + return cache.get(anIndex); + } } \ No newline at end of file diff --git a/source/mir/generator/CompositeGeneratorLibrary.java b/source/mir/generator/CompositeGeneratorLibrary.java index d1c5651b..324363fc 100755 --- a/source/mir/generator/CompositeGeneratorLibrary.java +++ b/source/mir/generator/CompositeGeneratorLibrary.java @@ -32,16 +32,16 @@ package mir.generator; import java.util.HashMap; import java.util.Map; -public class CompositeGeneratorLibrary implements Generator.GeneratorLibrary { +public class CompositeGeneratorLibrary implements Generator.Library { private Map generatorLibraries; - private Generator.GeneratorLibrary defaultLibrary = null; + private Generator.Library defaultLibrary = null; private static String LIBRARY_QUALIFIER_SEPARATOR = "::"; public CompositeGeneratorLibrary() { generatorLibraries = new HashMap(); } - public void addLibrary(String aQualifier, Generator.GeneratorLibrary aLibrary, boolean anIsDefault) { + public void addLibrary(String aQualifier, Generator.Library aLibrary, boolean anIsDefault) { if (anIsDefault || defaultLibrary == null) { defaultLibrary = aLibrary; } @@ -53,14 +53,14 @@ public class CompositeGeneratorLibrary implements Generator.GeneratorLibrary { String qualifier; String libraryName; int position; - Generator.GeneratorLibrary library; + Generator.Library library; position = anIdentifier.indexOf( LIBRARY_QUALIFIER_SEPARATOR ); if (position>=0) { libraryName = anIdentifier.substring(0, position); qualifier = anIdentifier.substring(position + LIBRARY_QUALIFIER_SEPARATOR.length()); - library = (Generator.GeneratorLibrary) generatorLibraries.get(libraryName); + library = (Generator.Library) generatorLibraries.get(libraryName); if (library==null) throw new GeneratorExc("CompositeGeneratorLibrary: library '"+libraryName+"' not found"); diff --git a/source/mir/generator/FreemarkerGenerator.java b/source/mir/generator/FreemarkerGenerator.java index a786a712..d4a4ee7b 100755 --- a/source/mir/generator/FreemarkerGenerator.java +++ b/source/mir/generator/FreemarkerGenerator.java @@ -30,20 +30,13 @@ package mir.generator; import java.io.PrintWriter; -import java.util.Arrays; +import java.io.File; +import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; -import java.util.Vector; - -import mir.log.LoggerWrapper; -import mir.util.GeneratorFormatAdapters; -import mir.util.RewindableIterator; - -import org.apache.commons.beanutils.MethodUtils; -import org.apache.commons.beanutils.PropertyUtils; import freemarker.template.FileTemplateCache; import freemarker.template.SimpleScalar; @@ -55,6 +48,11 @@ import freemarker.template.TemplateModel; import freemarker.template.TemplateModelException; import freemarker.template.TemplateModelRoot; import freemarker.template.TemplateScalarModel; +import mir.log.LoggerWrapper; +import mir.util.GeneratorFormatAdapters; +import mir.util.RewindableIterator; +import org.apache.commons.beanutils.MethodUtils; +import org.apache.commons.beanutils.PropertyUtils; public class FreemarkerGenerator implements Generator { @@ -91,7 +89,7 @@ public class FreemarkerGenerator implements Generator { return new IteratorAdapter(anIterator); } - private static TemplateMethodModel makeFunctionAdapter(Generator.GeneratorFunction aFunction) { + private static TemplateMethodModel makeFunctionAdapter(Generator.Function aFunction) { return new FunctionAdapter(aFunction); } @@ -102,12 +100,13 @@ public class FreemarkerGenerator implements Generator { public static TemplateModel makeAdapter(Object anObject) throws TemplateModelException { if (anObject == null) return null; + if (anObject instanceof TemplateModel) return (TemplateModel) anObject; - else if (anObject instanceof Generator.GeneratorFunction) - return makeFunctionAdapter((Generator.GeneratorFunction) anObject); + else if (anObject instanceof Generator.Function) + return makeFunctionAdapter((Generator.Function) anObject); else if (anObject instanceof Integer) - return makeStringAdapter(((Integer) anObject).toString()); + return makeStringAdapter(anObject.toString()); else if (anObject instanceof Boolean) { if (((Boolean) anObject).booleanValue()) return makeStringAdapter("1"); @@ -122,14 +121,6 @@ public class FreemarkerGenerator implements Generator { return makeIteratorAdapter((Iterator) anObject); else if (anObject instanceof List) return makeIteratorAdapter(((List) anObject).iterator()); - else if (anObject instanceof Object[]){ - if(((Object[])anObject).length <= 1){ - Object[] array = (Object[]) anObject; - return makeAdapter(array[0]); - } else { - return makeIteratorAdapter(Arrays.asList((Object[]) anObject).iterator()); - } - } else if (anObject instanceof Number) return makeAdapter(new GeneratorFormatAdapters.NumberFormatAdapter((Number) anObject)); else if (anObject instanceof Date) @@ -189,7 +180,7 @@ public class FreemarkerGenerator implements Generator { private IteratorAdapter(Iterator anIterator) { iterator = anIterator; - valuesCache = new Vector(); + valuesCache = new ArrayList(); position=0; @@ -257,7 +248,7 @@ public class FreemarkerGenerator implements Generator { private ListAdapter(List aList) { list = aList; - valuesCache = new Vector(); + valuesCache = new ArrayList(); position=0; } @@ -307,9 +298,9 @@ public class FreemarkerGenerator implements Generator { } private static class FunctionAdapter implements TemplateMethodModel { - private Generator.GeneratorFunction function; + private Generator.Function function; - public FunctionAdapter(Generator.GeneratorFunction aFunction) { + public FunctionAdapter(Generator.Function aFunction) { function = aFunction; } @@ -360,11 +351,11 @@ public class FreemarkerGenerator implements Generator { } } - public static class FreemarkerGeneratorLibrary implements GeneratorLibrary { + public static class FreemarkerGeneratorLibrary implements Library { private FileTemplateCache templateCache; - public FreemarkerGeneratorLibrary(String aTemplateRoot) { - templateCache = new FileTemplateCache( aTemplateRoot+"/" ); + public FreemarkerGeneratorLibrary(File aTemplateRoot) { + templateCache = new FileTemplateCache(aTemplateRoot); templateCache.setLoadingPolicy(FileTemplateCache.LOAD_ON_DEMAND); } @@ -372,22 +363,23 @@ public class FreemarkerGenerator implements Generator { Template template = (Template) templateCache.getItem(anIdentifier, "template"); if (template==null) { - throw new GeneratorExc("FreemarkerGeneratorLibrary: Can't find template "+templateCache.getDirectory()+anIdentifier); + throw new GeneratorExc("FreemarkerGeneratorLibrary: Can't find template "+templateCache.getDirectory()+"/"+anIdentifier); } return new FreemarkerGenerator(template); } } - public static class FreemarkerGeneratorLibraryFactory implements GeneratorLibraryFactory { - private String basePath; + public static class FreemarkerGeneratorLibraryFactory implements LibraryFactory { + private File basePath; - public FreemarkerGeneratorLibraryFactory(String aBasePath) { + public FreemarkerGeneratorLibraryFactory(File aBasePath) { basePath = aBasePath; } - public GeneratorLibrary makeLibrary(String anInitializationString) { - return new FreemarkerGeneratorLibrary(basePath+anInitializationString); + public Library makeLibrary(String anInitializationString) { + // todo: the initialization string should be parsed + return new FreemarkerGeneratorLibrary(new File(basePath, anInitializationString)); }; } } diff --git a/source/mir/generator/Generator.java b/source/mir/generator/Generator.java index 3f10ca79..805d0ccc 100755 --- a/source/mir/generator/Generator.java +++ b/source/mir/generator/Generator.java @@ -30,28 +30,34 @@ package mir.generator; -import java.io.*; +import java.io.PrintWriter; +import java.io.Reader; import java.util.List; import java.util.Map; import mir.log.LoggerWrapper; +/** + * Interface representing a "generator", typically a template engine/ + */ public interface Generator { public void generate(Object anOutputWriter, Map aValues, LoggerWrapper aLogger) throws GeneratorExc, GeneratorFailure; - public static interface GeneratorLibrary { + public static interface Library { public Generator makeGenerator(String anIdentifier) throws GeneratorExc, GeneratorFailure; } - public static interface GeneratorLibraryFactory { - public GeneratorLibrary makeLibrary(String anInitializationString); + public static interface LibraryFactory { + public Library makeLibrary(String anInitializationString) throws GeneratorExc, GeneratorFailure ; } - public static interface GeneratorFunction { + /** interface for a generator implementation independent function */ + public static interface Function { + /** performs the function with the given parameters */ public Object perform(List aParameters) throws GeneratorExc, GeneratorFailure; } - public static interface GeneratorTransformer { + public static interface Transformer { public void perform(Reader aSource, PrintWriter anOutput) throws GeneratorExc, GeneratorFailure; } } diff --git a/source/mir/generator/GeneratorHelper.java b/source/mir/generator/GeneratorHelper.java new file mode 100755 index 00000000..298723dd --- /dev/null +++ b/source/mir/generator/GeneratorHelper.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.generator; + +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.ArrayList; +import java.util.List; + +import mir.entity.adapter.EntityIteratorAdapter; +import mir.util.CachingRewindableIterator; +import mir.bundle.Bundle; +import mir.util.generator.BundleGeneratorFunction; +import mircoders.global.MirGlobal; + + + +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{ + try { + Map result = new HashMap(); + MirGlobal.localizer().producerAssistant().initializeGenerationValueSet(result); + + Object languages = new CachingRewindableIterator(new EntityIteratorAdapter("", "id", 30, MirGlobal.localizer().dataModel().adapterModel(), "language")); + + Object topics = new CachingRewindableIterator(new EntityIteratorAdapter("", "id", 30, MirGlobal.localizer().dataModel().adapterModel(), "topic")); + + Object articleTypes = new CachingRewindableIterator(new EntityIteratorAdapter("", "id", 30, MirGlobal.localizer().dataModel().adapterModel(), "articleType")); + + Object commentStatuses = new CachingRewindableIterator(new EntityIteratorAdapter("", "id", 30, MirGlobal.localizer().dataModel().adapterModel(), "commentStatus")); + + result.put("commentstatuses", commentStatuses); + result.put("articletypes", articleTypes); + result.put("languages", languages); + result.put("topics", topics); + + List bundles = new ArrayList(); + for (int i=0; iTitle:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ + private interface VelocityAdapter { + public Object getOriginal(); + } + + /** + * + * @param anObject + * @return + */ + public static Object unmakeAdapter(Object anObject) { + if (anObject instanceof VelocityAdapter) { + return ((VelocityAdapter) anObject).getOriginal(); + } + else + return anObject; + } + + /** + * + * @param anObject + * @return + */ + public static Object makeAdapter(Object anObject) { + if (anObject == null) + return null; + + if (anObject instanceof Context) + return anObject; + + else if (anObject instanceof Generator.Function) + return makeFunctionAdapter((Generator.Function) anObject); + else if (anObject instanceof Integer) + return anObject; + else if (anObject instanceof Boolean) + return anObject; + else if (anObject instanceof String) + return anObject; + else if (anObject instanceof Map) + return makeMapAdapter((Map) anObject); + else if (anObject instanceof Iterator) + return makeIteratorAdapter((Iterator) anObject); + else if (anObject instanceof List) + return makeListAdapter(((List) anObject)); + else if (anObject instanceof Number) + return makeAdapter(new GeneratorFormatAdapters.NumberFormatAdapter((Number) anObject)); + else if (anObject instanceof Date) + return makeAdapter(new GeneratorFormatAdapters.DateFormatAdapter((Date) anObject)); + else + return makeBeanAdapter(anObject); + } + + /** + * + *

Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ + public static class FunctionAdapter implements VelocityAdapter { + private Function function; + + public Object getOriginal() { + return function; + } + + private FunctionAdapter(Function aFunction) { + function = aFunction; + } + + public Object call(Object aParameters[]) throws GeneratorExc { + List parameters = new Vector(); + + for (int i = 0; iTitle:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ + private static class MapAdapter implements Context, VelocityAdapter { + private Map map; + private Map valuesCache; + + private MapAdapter(Map aMap) { + map = aMap; + valuesCache = new HashMap(); + } + + public Object getOriginal() { + return map; + } + + public boolean containsKey(Object aKey) { + return map.containsKey(aKey); + } + + public Object get(String aKey) { + try { + if (!valuesCache.containsKey(aKey)) { + Object value = map.get(aKey); + + if (value == null && !map.containsKey(aKey)) { + return "no key "+aKey+" available"; + } + else + valuesCache.put(aKey, makeAdapter(value)); + } + + return valuesCache.get(aKey); + } + catch (Throwable t) { + throw new GeneratorFailure(t); + } + } + + public Object[] getKeys() { + return new Object[] {}; + } + + public Object put(String aKey, Object aValue) { + valuesCache.remove(aKey); + map.put(aKey, unmakeAdapter(aValue)); + + return aValue; + } + + public Object remove(java.lang.Object key) { + return null; + } + } + + /** + * + *

Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ + private static class IteratorAdapter extends AbstractList implements VelocityAdapter { + private Iterator iterator; + private List valuesCache; + + private IteratorAdapter(Iterator anIterator) { + iterator = anIterator; + + valuesCache = new Vector(); + + if (iterator instanceof RewindableIterator) { + ((RewindableIterator) iterator).rewind(); + } + } + + private void getUntil(int anIndex) { + while ((anIndex==-1 || valuesCache.size()<=anIndex) && iterator.hasNext()) + { + valuesCache.add(makeAdapter(iterator.next())); + } + }; + + public Object getOriginal() { + return iterator; + } + + public Object get(int anIndex) { + Object result; + + getUntil(anIndex); + + if (anIndexTitle:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ + private static class ListAdapter extends AbstractList implements VelocityAdapter { + private List list; + private List valuesCache; + + private ListAdapter(List aList) { + list = aList; + + valuesCache = new Vector(); + } + + private void getUntil(int anIndex) { + while ((anIndex==-1 || valuesCache.size()<=anIndex) && valuesCache.size()Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ + private static class BeanAdapter implements Context, VelocityAdapter { + private Object object; + + public BeanAdapter(Object anObject) { + object = anObject; + } + + public boolean containsKey(Object key) { + return true; + } + + public Object getOriginal() { + return object; + } + + public Object get(String aKey) { + try { + if (PropertyUtils.isReadable(object, aKey)) + return makeAdapter(PropertyUtils.getSimpleProperty(object, aKey)); + else + return makeAdapter(MethodUtils.invokeExactMethod(object, "get", aKey)); + } + catch (Throwable t) { + throw new GeneratorFailure(t); + } + } + + public Object[] getKeys() { + return new Object[] {}; + } + + public Object put(String aKey, Object aValue) { + try { + if (PropertyUtils.isWriteable(object, aKey)) + PropertyUtils.setSimpleProperty(object, aKey, unmakeAdapter(aValue)); + else + MethodUtils.invokeExactMethod(object, "set", new Object[] {aKey, unmakeAdapter(aValue)}); + + return this; + } + catch (Throwable t) { + throw new GeneratorFailure(t); + } + } + + public Object remove(Object aKey) { + throw new RuntimeException("BeanAdapter.remove not supported"); + } + } + + /** + * + *

Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ + private static class VelocityLoggerWrapper implements LogSystem { + private LoggerWrapper logger; + + public VelocityLoggerWrapper(LoggerWrapper aLogger) { + logger = aLogger; + } + + public void init(RuntimeServices aRuntimeServices) { + } + + public void logVelocityMessage(int aLevel, String aMessage) { + switch (aLevel) { + case DEBUG_ID: + logger.debug(aMessage); + break; + case ERROR_ID: + logger.error(aMessage); + break; + case INFO_ID: + logger.info(aMessage); + break; + default: + logger.warn(aMessage); + break; + } + } + } + + /** + * + *

Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ + public static class VelocityGeneratorLibrary implements Library { + private VelocityEngine engine; + + public VelocityGeneratorLibrary(File aTemplateRoot) throws GeneratorExc, GeneratorFailure { + try { + engine = new VelocityEngine(); + try { + engine.setProperty(VelocityEngine.RESOURCE_LOADER, "file"); + engine.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.FileResourceLoader"); + engine.setProperty("file.resource.loader.path", aTemplateRoot.getAbsolutePath()); + engine.setProperty("file.resource.loader.cache", "true"); + } + catch (Throwable t) { + logger.error("Error while constructing library: " + t.toString()); + + throw new GeneratorFailure(t); + } + + try { + engine.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM, new VelocityLoggerWrapper(logger)); + } + catch (Throwable t) { + logger.error(VelocityEngine.RUNTIME_LOG_LOGSYSTEM); + + } + engine.init(); + } + catch (Throwable t) { + t.printStackTrace(logger.asPrintWriter(logger.ERROR_MESSAGE)); + + logger.error("Failed to set up a VelocityGeneratorLibrary: " + t.toString()); + throw new GeneratorFailure(t); + } + } + + public Generator makeGenerator(String anIdentifier) throws GeneratorExc, GeneratorFailure { + return new VelocityGenerator(anIdentifier, this); + } + } + + /** + * + *

Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ + public static class VelocityGeneratorLibraryFactory implements LibraryFactory { + private File basePath; + + public VelocityGeneratorLibraryFactory(File aBasePath) { + basePath = aBasePath; + } + + public Library makeLibrary(String anInitializationString) throws GeneratorExc, GeneratorFailure { + return new VelocityGeneratorLibrary(new File(basePath, anInitializationString)); + }; + } +} diff --git a/source/mir/generator/tal/CachingFileLoader.java b/source/mir/generator/tal/CachingFileLoader.java new file mode 100755 index 00000000..c9f042b9 --- /dev/null +++ b/source/mir/generator/tal/CachingFileLoader.java @@ -0,0 +1,138 @@ +/* + * 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.generator.tal; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class CachingFileLoader { + private Map cachedObjects; + private List history; + private int capacity; + private CachedFileObjectFactory factory; + + public CachingFileLoader(int aCapacity, CachedFileObjectFactory aFactory) { + capacity = aCapacity; + cachedObjects = new HashMap(); + history = new ArrayList(); + factory = aFactory; + } + + private void cacheObject(String aFilename, long aLastModified, Object anObject) { + synchronized (this) { + history.remove(aFilename); + history.add(aFilename); + while (history.size()>capacity && history.size()>0) { + history.remove(0); + } + cachedObjects.put(aFilename, new CachedObject(aFilename, aLastModified, anObject)); + } + } + + private Object constructObject(String aFilename) throws FileNotFoundException { + File file = new File(aFilename); + BufferedInputStream inputStream = new BufferedInputStream( + new FileInputStream(file), 8192); + try { + Object result = factory.constructObject(inputStream); + cacheObject(aFilename, file.lastModified(), result); + + return result; + } + finally { + try { + inputStream.close(); + } + catch (Throwable t) { + } + } + } + + private void revatilize(String aFilename) { + synchronized (this) { + history.remove(aFilename); + history.add(aFilename); + } + } + + private class CachedObject { + private String filename; + private long lastModified; + private Object object; + + public CachedObject(String aFilename, long aLastModified, Object anObject) { + filename = aFilename; + lastModified = aLastModified; + object = anObject; + } + + public Object getObject() { + return object; + } + + public String getFilename() { + return filename; + } + + public long getLastModified() { + return lastModified; + } + } + + public Object retrieveFile(String aFilename) throws FileNotFoundException { + synchronized (this) { + if (!cachedObjects.containsKey(aFilename)) { + return constructObject(aFilename); + } + + CachedObject cachedObject = (CachedObject) cachedObjects.get(aFilename); + File file = new File(aFilename); + if (file.lastModified() != cachedObject.getLastModified()) { + return constructObject(aFilename); + } + + revatilize(aFilename); + + return cachedObject.getObject(); + } + } + + public interface CachedFileObjectFactory { + Object constructObject(InputStream aStream); + } +} \ No newline at end of file diff --git a/source/mir/generator/tal/MirExpressionParser.java b/source/mir/generator/tal/MirExpressionParser.java new file mode 100755 index 00000000..3413fc5d --- /dev/null +++ b/source/mir/generator/tal/MirExpressionParser.java @@ -0,0 +1,154 @@ +/* + * 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.generator.tal; + +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import mir.generator.tal.interfaces.TALExpressionParser; +import mir.util.ParameterExpander; +import mir.util.RewindableIterator; + +public class MirExpressionParser implements TALExpressionParser { + public Object preparseExpression(String anExpression) { + return anExpression; + } + public Object preparseStringExpression(String anExpression) { + return anExpression; + } + + public Object preparseBooleanExpression(String anExpression) { + return anExpression; + } + + public Object preparseReferenceExpression(String anExpression) { + return anExpression; + } + + public Object preparseListExpression(String anExpression) { + return anExpression; + } + + public Object preparseTRUE() { + return "1==1"; + } + + public Object preparseFALSE() { + return "0==1"; + } + + public Object evaluateExpression(Object aContext, Object aPreparsedExpression) { + try { + return ParameterExpander.evaluateExpression(aContext, (String) aPreparsedExpression); + } + catch (Throwable t) { + throw new TALFailure(t); + } + } + + public String evaluateStringExpression(Object aContext, Object aPreparsedExpression) { + try { + return ParameterExpander.expandExpression(aContext, (String) aPreparsedExpression); + } + catch (Throwable t) { + throw new TALFailure(t); + } + } + + public boolean evaluateBooleanExpression(Object aContext, Object aPreparsedExpression) { + try { + return ParameterExpander.evaluateBooleanExpression(aContext, (String) aPreparsedExpression); + } + catch (Throwable t) { + throw new TALFailure(t); + } + } + + public Iterator evaluateListExpression(Object aContext, Object aPreparsedExpression) { + try { + Object list = ParameterExpander.evaluateExpression(aContext, (String) aPreparsedExpression); + + if (list instanceof List) + return ((List) list).iterator(); + + if (list instanceof RewindableIterator) { + ((RewindableIterator) list).rewind(); + return (RewindableIterator) list; + } + + if (list instanceof Iterator) { + return (Iterator) list; + } + + throw new TALExc("Not a list: " + list); + } + catch (Throwable t) { + throw new TALFailure(t); + } + } + + public void processAssignment(Object aContext, Object aPreparsedReferenceExpression, Object aPreparsedExpression) { + try { + ParameterExpander.setValueForKey( (Map) aContext, (String) aPreparsedReferenceExpression, ParameterExpander.evaluateExpression(aContext, (String) aPreparsedExpression)); + } + catch (Throwable t) { + throw new TALFailure(t); + } + } + + public void processDirectAssignment(Object aContext, Object aPreparsedReferenceExpression, Object aValue) { + try { + ParameterExpander.setValueForKey( (Map) aContext, (String) aPreparsedReferenceExpression, aValue); + } + catch (Throwable t) { + throw new TALFailure(t); + } + } + + public void processPseudoAssignment(Object aContext, String aName, Object aValue) { + try { + ParameterExpander.setValueForKey( (Map) aContext, aName, aValue); + } + catch (Throwable t) { + throw new TALFailure(t); + } + } + + public Object evaluatePseudoVariable(Object aContext, String aName) { + try { + return ParameterExpander.getObjectField(aContext, aName); + } + catch (Throwable t) { + throw new TALFailure(t); + } + } +} \ No newline at end of file diff --git a/source/mir/producer/NodedProducerFactory.java b/source/mir/generator/tal/SimpleTemplateNodeLibraryRegistry.java similarity index 57% rename from source/mir/producer/NodedProducerFactory.java rename to source/mir/generator/tal/SimpleTemplateNodeLibraryRegistry.java index 6df430ba..561f50a4 100755 --- a/source/mir/producer/NodedProducerFactory.java +++ b/source/mir/generator/tal/SimpleTemplateNodeLibraryRegistry.java @@ -18,58 +18,42 @@ * 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. + * 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; +package mir.generator.tal; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; import java.util.Map; -import java.util.Vector; +import java.util.HashMap; -public class NodedProducerFactory implements ProducerFactory { - private ProducerNode rootNode; - private List verbs; - private String name; +import mir.generator.tal.template.TemplateNodeLibraryRegistry; +import mir.generator.tal.template.TemplateNodeLibrary; - public NodedProducerFactory(String aName, ProducerNode aRootNode) { - rootNode = aRootNode; - verbs = new Vector(); - name = aName; - } +public class SimpleTemplateNodeLibraryRegistry implements TemplateNodeLibraryRegistry { + private Map urlToLibrary; + private Map prefixToLibrary; - public void addVerb(String aName, String aDescription) { - verbs.add(new SimpleProducerVerb(aName, aDescription)); + public SimpleTemplateNodeLibraryRegistry() { + urlToLibrary = new HashMap(); + prefixToLibrary = new HashMap(); } - public String getName() { - return name; + public void registerTemplateNodeLibrary(String aPrefix, String aUrl, TemplateNodeLibrary aLibrary) { + urlToLibrary.put(aUrl, aLibrary); + prefixToLibrary.put(aPrefix, aLibrary); } - public mir.producer.Producer makeProducer(String aVerb, Map aBasicValueSet) throws ProducerFailure { - Map baseValues; - - try { - baseValues = new HashMap(); - baseValues.putAll(aBasicValueSet); - - return new NodedProducer(rootNode, aVerb, baseValues); - } - catch (Throwable t) { - throw new ProducerFailure(t.getMessage(), t); - } - }; + public TemplateNodeLibrary findLibraryForUrl(String aUrl) { + return (TemplateNodeLibrary) urlToLibrary.get(aUrl); + } - public Iterator verbs() { - return verbs.iterator(); - }; + public TemplateNodeLibrary findLibraryForPrefix(String aPrefix) { + return (TemplateNodeLibrary) prefixToLibrary.get(aPrefix); + } } - diff --git a/source/mir/generator/tal/TALExc.java b/source/mir/generator/tal/TALExc.java new file mode 100755 index 00000000..f722d2cc --- /dev/null +++ b/source/mir/generator/tal/TALExc.java @@ -0,0 +1,38 @@ +/* + * 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.generator.tal; + +import multex.Exc; + +public class TALExc extends Exc { + public TALExc(String aMessage) { + super(aMessage); + } +} diff --git a/source/mir/generator/tal/TALFailure.java b/source/mir/generator/tal/TALFailure.java new file mode 100755 index 00000000..d15ebf5d --- /dev/null +++ b/source/mir/generator/tal/TALFailure.java @@ -0,0 +1,42 @@ +/* + * 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.generator.tal; + +import multex.Failure; + +public class TALFailure extends Failure { + public TALFailure(String msg,Throwable cause) { + super(msg,cause); + } + + public TALFailure(Throwable aCause) { + this (aCause.getMessage(), aCause); + } +} diff --git a/source/mir/generator/tal/TALTemplateEngine.java b/source/mir/generator/tal/TALTemplateEngine.java new file mode 100755 index 00000000..aa3fb763 --- /dev/null +++ b/source/mir/generator/tal/TALTemplateEngine.java @@ -0,0 +1,116 @@ +/* + * 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.generator.tal; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.Map; +import java.util.List; + +import mir.generator.tal.interfaces.TALExpressionParser; +import mir.generator.tal.template.*; +import mir.util.StringRoutines; + +public class TALTemplateEngine implements TemplateLibrary { + private TALExpressionParser expressionParser; + private File basePath; + private CachingFileLoader loader; + + private SimpleTemplateNodeLibraryRegistry registry; + + public TALTemplateEngine(TALExpressionParser anExpressionParser, File aBasePath) { + expressionParser = anExpressionParser; + basePath = aBasePath; + loader = new CachingFileLoader(100, new TemplateFactory()); + + registry = new SimpleTemplateNodeLibraryRegistry(); + + registerTemplateNodeLibrary("tal", "http://xml.zope.org/namespaces/tal", + new CoreTemplateNodeLibrary("tal", "http://xml.zope.org/namespaces/tal")); + registerTemplateNodeLibrary("metal", "http://xml.zope.org/namespaces/metal", + new MacroTemplateNodeLibrary("metal", "http://xml.zope.org/namespaces/metal")); + } + + public void registerTemplateNodeLibrary(String aPrefix, String aUrl, TemplateNodeLibrary aLibrary) { + registry.registerTemplateNodeLibrary(aPrefix, aUrl, aLibrary); + } + + public Template loadTemplate(String aName) throws IOException, TemplateProcessingException { + List parts = StringRoutines.splitString(aName, "#"); + + if (parts.size()!=1 && parts.size()!=2) { + throw new TemplateProcessingException("Invalid template name: " + aName); + } + + File location = new File(basePath, (String) parts.get(0)); + + Template baseTemplate = (Template) loader.retrieveFile(location.getCanonicalPath()); + + if (baseTemplate!=null && parts.size()>1) { + Map definitions = (Map) baseTemplate.getContext().get(MacroTemplateNodeLibrary.MACRO_DEFINITIONS_KEY); + if (definitions==null || !definitions.containsKey(parts.get(1))) { + throw new TemplateProcessingException("No macro '"+(String) parts.get(1)+"' found in template '" + (String) parts.get(0) + "'"); + } + + return new Template(expressionParser, (TemplateNode) definitions.get(parts.get(1)), baseTemplate.getContext()); + } + else { + return baseTemplate; + } + + + +// public Template(TALExpressionParser aParser, TemplateNode aRootNode, Map aTemplateContext) { + } + + public Template lookupTemplate(String aName) throws TemplateProcessingException { + try { + return loadTemplate(aName); + } + catch (IOException e) { + throw new TemplateProcessingException("Can't load template " + aName + ": " + e.toString(), e); + } + } + + private class TemplateFactory implements CachingFileLoader.CachedFileObjectFactory { + public Object constructObject(InputStream aStream) { + try { + TALTemplateParser parser = new TALTemplateParser(registry); + + return parser.parse(aStream, expressionParser); + } + catch (Throwable t) { + throw new TALFailure(t); + } + } + } +} \ No newline at end of file diff --git a/source/mir/generator/tal/TALTemplateParser.java b/source/mir/generator/tal/TALTemplateParser.java new file mode 100755 index 00000000..ff1596f5 --- /dev/null +++ b/source/mir/generator/tal/TALTemplateParser.java @@ -0,0 +1,223 @@ +/* + * 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.generator.tal; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.StringReader; +import java.util.Iterator; +import java.util.Map; +import java.util.HashMap; + +import mir.generator.tal.interfaces.TALExpressionParser; +import mir.generator.tal.template.CompositeTemplateNode; +import mir.generator.tal.template.PlainTextTemplateNode; +import mir.generator.tal.template.Template; +import mir.generator.tal.template.TemplateNodeLibrary; +import mir.generator.tal.template.TemplateNode; +import mir.generator.tal.template.TemplateNodeLibraryRegistry; +import mir.util.HTMLRoutines; +import mir.util.xml.SectionHandler; +import mir.util.xml.XMLName; +import mir.util.xml.XMLParserEngine; +import mir.util.xml.XMLParserExc; +import mir.util.xml.XMLParserFailure; +import mir.util.xml.XMLReaderTool; + +public class TALTemplateParser { + private TemplateNodeLibraryRegistry registry; + + public TALTemplateParser(TemplateNodeLibraryRegistry aRegistry) { + registry = aRegistry; + } + + public Template parse(String aData, TALExpressionParser aParser) throws TALExc, TALFailure { + return parse(new StringReader(aData), aParser); + } + + public Template parse(File aFile, TALExpressionParser aParser) throws TALExc, TALFailure { + try { + return parse(new BufferedInputStream(new FileInputStream(aFile), 1024*128), aParser); + } + catch (FileNotFoundException e) { + throw new TALFailure(e); + } + } + public Template parse(InputStream anInputStream, TALExpressionParser aParser) throws TALExc, TALFailure { + return parse(new InputStreamReader(anInputStream), aParser); + } + + public Template parse(Reader aReader, TALExpressionParser aParser) throws TALExc, TALFailure { + Map templateContext = new HashMap(); + TALHandler handler = new TALHandler(aParser, templateContext); + + try { + XMLParserEngine.getInstance().parse("html", aReader, handler); + } + catch (XMLParserExc e) { + throw new TALFailure(e); + } + + return new Template(aParser, handler.getNode(), templateContext); + } + + protected class TALHandler implements SectionHandler { + private CompositeTemplateNode compositeNode; + private StringBuffer data; + private StringBuffer plainData; + private TALExpressionParser parser; + private String currentTag; + private TemplateNodeLibrary library; + private XMLName tag; + private Map attributes; + private Map templateContext; + + public TALHandler(TALExpressionParser aParser, Map aTemplateContext) { + parser = aParser; + data = new StringBuffer(); + plainData = new StringBuffer(); + compositeNode = new CompositeTemplateNode(); + templateContext = aTemplateContext; + } + + private void flushData() { + if (data.length()!=0) { + compositeNode.appendSubNode(new PlainTextTemplateNode(data.toString(), plainData.toString())); + data.delete(0, data.length()); + plainData.delete(0, plainData.length()); + } + } + + public void extra(String anExtraData) throws XMLParserExc, XMLParserFailure { + appendCode(anExtraData); + } + + public TemplateNodeLibrary findLibrary(XMLName aName) { + TemplateNodeLibrary result = null; + + if (aName.getNamespaceURI()!=null) { + result = registry.findLibraryForUrl(aName.getNamespaceURI()); + } + + if ((result == null) && (aName.getPrefix()!=null) && (aName.getPrefix().length()>0)) { + result = registry.findLibraryForPrefix(aName.getPrefix()); + } + + return result; + } + + public SectionHandler startElement(mir.util.xml.XMLName aTag, Map anAttributes) throws XMLParserExc { + library = findLibrary(aTag); + + Iterator i = anAttributes.keySet().iterator(); + while (library==null && i.hasNext()) { + library=findLibrary((XMLName) i.next()); + } + + currentTag = XMLReaderTool.normalizeXMLName(aTag); + + if (library == null) { + appendCode("<"+currentTag); + i = anAttributes.entrySet().iterator(); + + while (i.hasNext()) { + Map.Entry entry = (Map.Entry) i.next(); + + appendCode(" "+ XMLReaderTool.normalizeXMLName((XMLName) entry.getKey())); + appendCode("=\""); + appendText((String) entry.getValue()); + appendCode("\""); + } + } + else { + tag = aTag; + attributes = anAttributes; + } + + return new TALHandler(parser, templateContext); + }; + + public void endElement(mir.util.xml.SectionHandler aHandler) throws XMLParserExc { + if (library == null) { + TemplateNode subNode = ((TALHandler) aHandler).getNode(); + if (subNode instanceof CompositeTemplateNode && + ((CompositeTemplateNode) subNode).isEmpty()) { + appendCode(" />"); + } + else { + appendCode(">"); + appendSubNode(subNode); + appendCode(""); + } + } + else { + appendSubNode( + library.constructTemplateNode(parser, tag, attributes, ((TALHandler) aHandler).getNode(), templateContext)); + tag = null; + attributes = null; + } + }; + + protected void appendSubNode(TemplateNode aNode) { + flushData(); + + compositeNode.appendSubNode(aNode); + } + + protected void appendCode(String aCode) { + data.append(aCode); + } + + protected void appendText(String aText) { + data.append(HTMLRoutines.encodeHTML(aText)); + plainData.append(aText); + } + + public void finishSection() throws XMLParserExc { + flushData(); + } + + public TemplateNode getNode() { + return compositeNode; + } + + public void characters(String aCharacters) throws XMLParserExc { + appendText(aCharacters); + } + + public void startSection() throws XMLParserExc, XMLParserFailure { + } + } +} diff --git a/source/mir/generator/tal/TALTest.java b/source/mir/generator/tal/TALTest.java new file mode 100755 index 00000000..1eb475d4 --- /dev/null +++ b/source/mir/generator/tal/TALTest.java @@ -0,0 +1,116 @@ +/* + * 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.generator.tal; + +import java.io.PrintWriter; +import java.io.File; +import java.util.HashMap; +import java.util.Map; + +import mir.generator.tal.interfaces.TALLogger; +import mir.generator.tal.template.Template; +import mir.generator.tal.template.TemplateLibrary; +import mir.generator.tal.template.TemplateProcessingException; +import mir.generator.tal.template.CoreTemplateNodeLibrary; +import mir.generator.tal.template.MacroTemplateNodeLibrary; + +public class TALTest { + public static void main(String args[]) { + try { + final SimpleTemplateNodeLibraryRegistry registry = new SimpleTemplateNodeLibraryRegistry(); + + registry.registerTemplateNodeLibrary("tal", "http://xml.zope.org/namespaces/tal", + new CoreTemplateNodeLibrary("tal", "http://xml.zope.org/namespaces/tal")); + registry.registerTemplateNodeLibrary("metal", "http://xml.zope.org/namespaces/metal", + new MacroTemplateNodeLibrary("metal", "http://xml.zope.org/namespaces/metal")); + + TemplateLibrary library = new TemplateLibrary() { + public Template lookupTemplate(String aTemplateName) throws TemplateProcessingException { + try { + TALTemplateParser parser = new TALTemplateParser(registry); + + if (aTemplateName.equals("a")) { + return parser.parse("bla" + + " " + + "bla die bla >" + + " ", new MirExpressionParser()); + } + else { + return parser.parse("hoi", new MirExpressionParser()); + } + } + catch (Throwable t) { + t.printStackTrace(); + System.out.println(t.toString()); + return null; + } + } + }; + + Map test = new HashMap(); + + Template template = library.lookupTemplate("a"); + + PrintWriter p = new PrintWriter(System.out); + + template.process(new HashMap(), p, new TALLogger.TALSystemOutLogger(), library); + + p.close(); + + } + catch (Throwable t) { + System.out.println("Exception: " + t.toString()); + t.printStackTrace(System.out); + } + } + public static void main2(String args[]) { + try { + TALTemplateEngine engine = new TALTemplateEngine( + new MirExpressionParser(), new File("m:/romania/mir/etc/producer/")); + + Map test = new HashMap(); + test.put("name", "zapata"); + + Template template = engine.loadTemplate("indy-ro-txt.html"); + + PrintWriter p = new PrintWriter(System.out); + + template.process(new Object(), p, new TALLogger.TALSystemOutLogger(), engine); + + p.close(); + + } + catch (Throwable t) { + System.out.println("Exception: " + t.toString()); + t.printStackTrace(System.out); + } + } +} \ No newline at end of file diff --git a/source/mir/generator/tal/interfaces/TALExpressionParser.java b/source/mir/generator/tal/interfaces/TALExpressionParser.java new file mode 100755 index 00000000..bc3106e9 --- /dev/null +++ b/source/mir/generator/tal/interfaces/TALExpressionParser.java @@ -0,0 +1,69 @@ +/* + * 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.generator.tal.interfaces; + +import java.util.Iterator; + +public interface TALExpressionParser { + public Object preparseExpression(String anExpression); + public Object preparseStringExpression(String anExpression); + public Object preparseBooleanExpression(String anExpression); + public Object preparseReferenceExpression(String anExpression); + public Object preparseListExpression(String anExpression); + public Object preparseTRUE(); + public Object preparseFALSE(); + + public Object evaluateExpression(Object aContext, Object aPreparsedExpression); + public String evaluateStringExpression(Object aContext, Object aPreparsedExpression); + public boolean evaluateBooleanExpression(Object aContext, Object aPreparsedExpression); + public Iterator evaluateListExpression(Object aContext, Object aPreparsedExpression); + public void processAssignment(Object aContext, Object aPreparsedReferenceExpression, Object aPreparsedExpression); + + /** + * process a direct assignment of an object to a preparsed reference expression + * + */ + public void processDirectAssignment(Object aContext, Object aPreparsedReferenceExpression, Object aValue); + + /** + * process an assigment to a pseudo variable. The pseudo variable will have a java + * identifier-like name. + * + */ + public void processPseudoAssignment(Object aContext, String aName, Object aValue); + + /** + * Retrieve the value of a pseudo variable + * + */ + public Object evaluatePseudoVariable(Object aContext, String aName); + +} \ No newline at end of file diff --git a/source/mir/generator/tal/interfaces/TALLogger.java b/source/mir/generator/tal/interfaces/TALLogger.java new file mode 100755 index 00000000..2f36c838 --- /dev/null +++ b/source/mir/generator/tal/interfaces/TALLogger.java @@ -0,0 +1,87 @@ +/* + * 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.generator.tal.interfaces; + +public interface TALLogger { + public void debug(String anObject, String aMessage); + public void info(String anObject, String aMessage); + public void warning(String anObject, String aMessage); + public void error(String anObject, String aMessage); + public void fatal(String anObject, String aMessage); + + /** + * Simple logging class that logs everything to System.out + */ + public class TALSystemOutLogger implements TALLogger { + public TALSystemOutLogger() { + } + + public void debug(String anObject, String aMessage) { + System.out.println("DEBUG: " + anObject + " " + aMessage); + } + + public void info(String anObject, String aMessage) { + System.out.println("INFO: " + anObject + " " + aMessage); + } + + public void warning(String anObject, String aMessage) { + System.out.println("WARNING: " + anObject + " " + aMessage); + } + + public void error(String anObject, String aMessage) { + System.out.println("ERROR: " + anObject + " " + aMessage); + } + + public void fatal(String anObject, String aMessage) { + System.out.println("FATAL: " + anObject + " " + aMessage); + } + } + + /** + * Simple logging class that discards all logging information. + */ + public class TALVoidLogger implements TALLogger { + public void debug(String anObject, String aMessage) { + } + + public void info(String anObject, String aMessage) { + } + + public void warning(String anObject, String aMessage) { + } + + public void error(String anObject, String aMessage) { + } + + public void fatal(String anObject, String aMessage) { + } + } +} \ No newline at end of file diff --git a/source/mir/generator/tal/template/CompositeTemplateNode.java b/source/mir/generator/tal/template/CompositeTemplateNode.java new file mode 100755 index 00000000..55a6cb0a --- /dev/null +++ b/source/mir/generator/tal/template/CompositeTemplateNode.java @@ -0,0 +1,98 @@ +/* + * 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.generator.tal.template; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import mir.generator.tal.interfaces.TALExpressionParser; +import mir.generator.tal.interfaces.TALLogger; + +/** + * Template node that is composed of a list of template nodes. + * + */ +public class CompositeTemplateNode implements TemplateNode { + private List parts; + + public CompositeTemplateNode() { + parts = new ArrayList(); + } + + /** {@inheritDoc} */ + public void process(TALExpressionParser aParser, Object aContext, StringBuffer aDestination, + TALLogger aLogger, Map aTemplateContext, TemplateLibrary aLibrary) throws TemplateProcessingException { + Iterator i = parts.iterator(); + + while (i.hasNext()) { + ((TemplateNode) i.next()).process(aParser, aContext, aDestination, aLogger, aTemplateContext, aLibrary); + } + } + + public String getPlainText() { + StringBuffer result = new StringBuffer(); + + Iterator i = parts.iterator(); + while (i.hasNext()) { + result.append(((TemplateNode) i.next()).getPlainText()); + } + + return result.toString(); + } + + public boolean isEmpty() { + return parts.isEmpty(); + } + + /** + * Adds a TemplateNode at the end of the chain. + */ + public void appendSubNode(TemplateNode aNode) { + if (aNode instanceof CompositeTemplateNode) { + Iterator i = ((CompositeTemplateNode) aNode).parts.iterator(); + while (i.hasNext()) { + appendSubNode((TemplateNode) i.next()); + } + } + else if (aNode instanceof PlainTextTemplateNode && + parts.size()>0 && + (parts.get(parts.size()-1) instanceof PlainTextTemplateNode)) { + + ((PlainTextTemplateNode) parts.get(parts.size()-1)).appendText(((PlainTextTemplateNode) aNode).getText()); + ((PlainTextTemplateNode) parts.get(parts.size()-1)).appendPlainText(((PlainTextTemplateNode) aNode).getPlainText()); + } + else { + parts.add(aNode); + } + } + +} diff --git a/source/mir/generator/tal/template/CoreTemplateNodeLibrary.java b/source/mir/generator/tal/template/CoreTemplateNodeLibrary.java new file mode 100755 index 00000000..e806deb9 --- /dev/null +++ b/source/mir/generator/tal/template/CoreTemplateNodeLibrary.java @@ -0,0 +1,380 @@ +/* + * 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.generator.tal.template; + +import java.util.*; + +import mir.generator.tal.interfaces.TALExpressionParser; +import mir.generator.tal.interfaces.TALLogger; +import mir.util.HTMLRoutines; +import mir.util.StringRoutines; +import mir.util.xml.XMLName; +import mir.util.xml.XMLParserExc; +import mir.util.xml.XMLReaderTool; + +public class CoreTemplateNodeLibrary implements TemplateNodeLibrary { + private String prefix; + private String uri; + + private boolean isOurTag(XMLName aName) { + return prefix.equals(aName.getPrefix()) || uri.equals(aName.getNamespaceURI()); + } + + public CoreTemplateNodeLibrary(String aPrefix, String aUri) { + prefix = aPrefix; + uri = aUri; + } + + private static final String CONDITION_ATTRIBUTE = "condition"; + private static final String REPEAT_ATTRIBUTE = "repeat"; + private static final String CONTENT_ATTRIBUTE = "content"; + private static final String ERROR_ATTRIBUTE = "on-error"; + private static final String REPLACE_ATTRIBUTE = "replace"; + private static final String DEFINITION_ATTRIBUTE = "define"; + private static final String OMITTAG_ATTRIBUTE = "omit-tag"; + private static final String ATTRIBUTE_ATTRIBUTE = "attributes"; + + public TemplateNode constructTemplateNode(TALExpressionParser aParser, XMLName aTag, Map anAttributes, + TemplateNode aChildTemplateNode, Map aTemplateContext) throws XMLParserExc { + TALBasicTemplateNode result = new TALBasicTemplateNode(XMLReaderTool.normalizeXMLName(aTag)); + result.setBody(aChildTemplateNode); + + if (isOurTag(aTag)) + result.setOmitTag(aParser.preparseTRUE()); + + Iterator i = anAttributes.entrySet().iterator(); + while (i.hasNext()) { + Map.Entry entry = (Map.Entry) i.next(); + XMLName name = (XMLName) entry.getKey(); + + if (!isOurTag(name)) { + result.addFixedAttribute(XMLReaderTool.normalizeXMLName(name), (String) entry.getValue()); + } + else { + if (name.getLocalName().equalsIgnoreCase(DEFINITION_ATTRIBUTE)) { + List definitions = StringRoutines.splitStringWithEscape((String) entry.getValue(), ';', '\\'); + + Iterator j = definitions.iterator(); + while (j.hasNext()) + { + List parts = StringRoutines.separateString((String) j.next(), " "); + + if (parts.size()==2) { + result.addDefinition(aParser.preparseReferenceExpression((String) parts.get(0)), aParser.preparseExpression((String) parts.get(1))); + } + } + } + else if (name.getLocalName().equalsIgnoreCase(CONDITION_ATTRIBUTE)) { + result.setCondition(aParser.preparseBooleanExpression((String) entry.getValue())); + } + else if (name.getLocalName().equalsIgnoreCase(CONTENT_ATTRIBUTE)) { + result.setContent(aParser.preparseStringExpression((String) entry.getValue())); + } + else if (name.getLocalName().equalsIgnoreCase(ERROR_ATTRIBUTE)) { + result.setError(aParser.preparseStringExpression((String) entry.getValue())); + } + else if (name.getLocalName().equalsIgnoreCase(OMITTAG_ATTRIBUTE)) { + if (((String) entry.getValue()).trim().length()==0) + result.setOmitTag(aParser.preparseTRUE()); + else + result.setOmitTag(aParser.preparseBooleanExpression((String) entry.getValue())); + } + else if (name.getLocalName().equalsIgnoreCase(REPLACE_ATTRIBUTE)) { + result.setOmitTag(aParser.preparseTRUE()); + result.setContent(aParser.preparseStringExpression((String) entry.getValue())); + } + else if (name.getLocalName().equalsIgnoreCase(REPEAT_ATTRIBUTE)) { + List parts = StringRoutines.separateString((String) entry.getValue(), " "); + + if (parts.size()==2) { + result.setRepeat(aParser.preparseReferenceExpression((String) parts.get(0)), aParser.preparseExpression((String) parts.get(1))); + } + } + else if (name.getLocalName().equalsIgnoreCase(ATTRIBUTE_ATTRIBUTE)) { + List attributes = StringRoutines.splitStringWithEscape((String) entry.getValue(), ';', '\\'); + + Iterator j = attributes.iterator(); + while (j.hasNext()) { + String value = (String) j.next(); + List parts = StringRoutines.separateString(value.trim(), " "); + + if (parts.size()==2) { + result.addModifiedAttribute((String) parts.get(0), aParser.preparseExpression((String) parts.get(1))); + } + else { + throw new XMLParserExc(ATTRIBUTE_ATTRIBUTE + " tag should have exactly 2 parts ("+value+")"); + } + } + } + } + } + + return result; + } + + public static class TALBasicTemplateNode implements TemplateNode { + private String tag; + private Map fixedAttributes; + private Map attributeModifiers; + + private List definitions; + private Object condition; + + private Object repeatVariable; + private Object repeatExpression; + private Object contentExpression; + private Object omitTagExpression; + private Object errorExpression; + + private TemplateNode body; + + public TALBasicTemplateNode(String aTag) { + tag = aTag; + + fixedAttributes = new HashMap(); + attributeModifiers = new HashMap(); + + definitions = new ArrayList(); + condition = null; + + repeatVariable = null; + repeatExpression = null; + contentExpression = null; + omitTagExpression = null; + + body = null; + } + + public void setBody(TemplateNode aBody) { + body = aBody; + } + + public void addFixedAttribute(String aKey, String aValue) { + fixedAttributes.put(aKey, aValue); + } + + public void addModifiedAttribute(String aKey, Object aValue) { + attributeModifiers.put(aKey, aValue); + } + + public void addDefinition(Object aKey, Object aValue) { + definitions.add(new Definition(aKey, aValue)); + } + + public void setCondition(Object aCondition) { + condition = aCondition; + } + + public void setRepeat(Object aRepeatVariable, Object aRepeatExpression) { + repeatVariable = aRepeatVariable; + repeatExpression = aRepeatExpression; + } + + public void setContent(Object aContentExpression) { + contentExpression = aContentExpression; + } + + public void setOmitTag(Object anOmitTagExpression) { + omitTagExpression = anOmitTagExpression; + } + + public void setError(Object anErrorExpression) { + errorExpression = anErrorExpression; + } + + public static class Definition { + private Object variable; + private Object expression; + + public Definition(Object aVariable, Object anExpression) { + variable = aVariable; + expression = anExpression; + } + + public Object getVariable() { + return variable; + } + + public Object getExpression() { + return expression; + } + } + + public void process(TALExpressionParser aParser, Object aContext, + StringBuffer aDestination, TALLogger aLogger, Map aTemplateContext, + TemplateLibrary aLibrary) throws TemplateProcessingException { + if (errorExpression != null) { + StringBuffer destination = new StringBuffer(); + + try { + outerProcess(aParser, aContext, destination, aLogger, aTemplateContext, aLibrary); + } + catch (Throwable t) { + try { +// destination.delete(0, destination.length()); + aParser.processPseudoAssignment(aContext, "exception", t); + destination.insert(0, aParser.evaluateStringExpression(aContext, errorExpression)); + destination.append(" >>>ERROR POSITION<<< "); + } + catch (Throwable s) { + throw new TemplateProcessingException(s); + } + } + finally { + aDestination.append(destination); + } + } + else { + outerProcess(aParser, aContext, aDestination, aLogger, aTemplateContext, aLibrary); + } + } + + public String getPlainText() { + return body.getPlainText(); + } + + public void outerProcess(TALExpressionParser aParser, Object aContext, + StringBuffer aDestination, TALLogger aLogger, Map aTemplateContext, + TemplateLibrary aLibrary) throws TemplateProcessingException { + + Object oldAttributes = aParser.evaluatePseudoVariable(aContext, "tagattributes"); + aParser.processPseudoAssignment(aContext, "tagattributes", Collections.unmodifiableMap(fixedAttributes)); + + Object oldContent = aParser.evaluatePseudoVariable(aContext, "tagcontent"); + aParser.processPseudoAssignment(aContext, "tagcontent", body.getPlainText()); + + try { + Iterator i; + + i = definitions.iterator(); + while (i.hasNext()) { + Definition d = (Definition) i.next(); + aParser.processAssignment(aContext, d.getVariable(), d.getExpression()); + } + + if (condition == null || aParser.evaluateBooleanExpression(aContext, condition)) { + if (repeatExpression != null) { + i = aParser.evaluateListExpression(aContext, repeatExpression); + + while (i.hasNext()) { + aParser.processDirectAssignment(aContext, repeatVariable, i.next()); + innerProcess(aParser, aContext, aDestination, aLogger, aTemplateContext, aLibrary); + } + } + else { + innerProcess(aParser, aContext, aDestination, aLogger, aTemplateContext, aLibrary); + } + } + } + finally { + try { + aParser.processPseudoAssignment(aContext, "tagattributes", oldAttributes); + aParser.processPseudoAssignment(aContext, "tagcontent", oldContent); + } + catch (Throwable t) { + } + } + }; + + private void innerProcess(TALExpressionParser aParser, Object aContext, + StringBuffer aDestination, TALLogger aLogger, Map aTemplateContext, TemplateLibrary aLibrary) + throws TemplateProcessingException { + + boolean omitTag = false; + StringBuffer content = aDestination; + + if (omitTagExpression != null) + omitTag = aParser.evaluateBooleanExpression(aContext, omitTagExpression); + + if (!omitTag) { + content = new StringBuffer(); + Map generatedAttributes = new HashMap(fixedAttributes); + + Iterator i = attributeModifiers.entrySet().iterator(); + while (i.hasNext()) { + Map.Entry entry = (Map.Entry) i.next(); + + generatedAttributes.put(entry.getKey(), aParser.evaluateStringExpression(aContext, entry.getValue())); + } + + aDestination.append("<"); + aDestination.append(tag); + + i = generatedAttributes.entrySet().iterator(); + while (i.hasNext()) { + Map.Entry entry = (Map.Entry) i.next(); + aDestination.append(" "); + aDestination.append(entry.getKey()); + aDestination.append("="); + aDestination.append("\""); + aDestination.append(HTMLRoutines.encodeHTML( (String) entry.getValue())); + aDestination.append("\""); + } + } + + try{ + if (contentExpression != null) { + content.append(aParser.evaluateStringExpression(aContext, contentExpression)); + } + else { + if (body != null) { + body.process(aParser, aContext, content, aLogger, aTemplateContext, aLibrary); + } + } + if (!omitTag) { + if (content.length()==0) { + aDestination.append(" />"); + } + else { + aDestination.append(">"); + aDestination.append(content); + aDestination.append(""); + } + } + } + catch (Throwable t) { + if (!omitTag) { + aDestination.append(content); + } + + if (t instanceof TemplateProcessingException) { + throw (TemplateProcessingException) t; + } + else if (t instanceof RuntimeException) { + throw (RuntimeException) t; + } + else throw new TemplateProcessingException(t.toString()); + } + } + } +} diff --git a/source/mir/generator/tal/template/MacroTemplateNodeLibrary.java b/source/mir/generator/tal/template/MacroTemplateNodeLibrary.java new file mode 100755 index 00000000..1310c7ba --- /dev/null +++ b/source/mir/generator/tal/template/MacroTemplateNodeLibrary.java @@ -0,0 +1,207 @@ +/* + * 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.generator.tal.template; + +import java.util.Map; +import java.util.Iterator; +import java.util.List; +import java.util.HashMap; + +import mir.generator.tal.interfaces.TALExpressionParser; +import mir.generator.tal.interfaces.TALLogger; +import mir.util.xml.XMLName; +import mir.util.xml.XMLParserExc; +import mir.util.xml.XMLReaderTool; +import mir.util.StringRoutines; +import mir.util.HTMLRoutines; + +public class MacroTemplateNodeLibrary implements TemplateNodeLibrary { + /** {@inheritDoc} */ + private static final String DEFINE_MACRO_ATTRIBUTE = "define-macro"; + private static final String USE_MACRO_ATTRIBUTE = "use-macro"; + private static final String DEFINE_SLOT_ATTRIBUTE = "define-slot"; + private static final String FILL_SLOT_ATTRIBUTE = "fill-macro"; + + public static final String MACRO_DEFINITIONS_KEY = "$" + MacroTemplateNodeLibrary.class.getName() + "$macro_definitions"; + public static final String ORPHANED_SLOTS_KEY = "$" + MacroTemplateNodeLibrary.class.getName() + "$macro_definitions"; + + private String prefix; + private String uri; + + + private boolean isOurTag(XMLName aName) { + return prefix.equals(aName.getPrefix()) || uri.equals(aName.getNamespaceURI()); + } + + public MacroTemplateNodeLibrary(String aPrefix, String aUri) { + prefix = aPrefix; + uri = aUri; + } + + public TemplateNode constructTemplateNode(TALExpressionParser anExpressionParser, XMLName aTag, Map anAttributes, + TemplateNode aChildTemplateNode, Map aTemplateContext) throws XMLParserExc { + + StringBuffer prefix = new StringBuffer(); + boolean useSurroundingTag = !(isOurTag(aTag)); + + prefix.append("<").append(XMLReaderTool.normalizeXMLName(aTag)); + String suffix = ""; + + String macroDefinition = null; + String slotDefinition = null; + String slotFill = null; + Object macroCallExpression = null; + + Iterator i = anAttributes.entrySet().iterator(); + + while (i.hasNext()) { + Map.Entry entry = (Map.Entry) i.next(); + XMLName name = (XMLName) entry.getKey(); + + if (!isOurTag(name)) { + prefix.append(" ").append(XMLReaderTool.normalizeXMLName(name)); + prefix.append("=\"").append(HTMLRoutines.encodeHTML( (String) entry.getValue())).append('"'); + } + else { + if (name.getLocalName().equalsIgnoreCase(DEFINE_MACRO_ATTRIBUTE)) { + macroDefinition = (String) entry.getValue(); + } + else if (name.getLocalName().equalsIgnoreCase(USE_MACRO_ATTRIBUTE)) { + macroCallExpression = anExpressionParser.preparseStringExpression((String) entry.getValue()); + } + else if (name.getLocalName().equalsIgnoreCase(DEFINE_SLOT_ATTRIBUTE)) { + slotDefinition = (String) entry.getValue(); + } + else if (name.getLocalName().equalsIgnoreCase(FILL_SLOT_ATTRIBUTE)) { + slotFill = (String) entry.getValue(); + } + } + } + prefix.append(">"); + + MacroTemplateNode result; + if (useSurroundingTag) { + result = new MacroTemplateNode(aChildTemplateNode, prefix.toString(), suffix, slotDefinition, slotFill); + } + else { + result = new MacroTemplateNode(aChildTemplateNode, "", "", slotDefinition, slotFill); + } + + if (macroCallExpression!=null) { + result.setMacroCall(macroCallExpression); + } + + if (macroDefinition!=null) { + macroDefinition = macroDefinition.trim(); + if (macroDefinition.length()==0) { + throw new XMLParserExc("Empty macro name"); + } + + Map definitions = (Map) aTemplateContext.get(MACRO_DEFINITIONS_KEY); + if (definitions==null) { + definitions=new HashMap(); + aTemplateContext.put(MACRO_DEFINITIONS_KEY, definitions); + } + + if (definitions.containsKey(macroDefinition)) { + throw new XMLParserExc("Duplicate macro name: " + macroDefinition); + } + + definitions.put(macroDefinition, result); + + Map slots = (Map) aTemplateContext.get(ORPHANED_SLOTS_KEY); + if (slots!=null) { + } + } + + return result; + } + + private class MacroTemplateNode implements TemplateNode { + private TemplateNode childNode; + private String prefix; + private String suffix; + + private Object macroCallTemplateExpression = null; + + private String slotDefinition; + private String slotFill; + + public MacroTemplateNode(TemplateNode aChildNode, String aPrefix, String aSuffix, + String aSlotDefinition, String aSlotFill) { + childNode = aChildNode; + prefix = aPrefix; + suffix = aSuffix; + + slotDefinition = aSlotDefinition; + slotFill = aSlotFill; + } + + public void setMacroCall(Object anExpression) { + macroCallTemplateExpression = anExpression; + } + + /** {@inheritDoc} */ + public void process(TALExpressionParser aParser, Object aContext, StringBuffer aDestination, + TALLogger aLogger, Map aTemplateContext, TemplateLibrary aLibrary) throws TemplateProcessingException { + + if (macroCallTemplateExpression!=null) { + String macroPath = aParser.evaluateStringExpression(aContext, macroCallTemplateExpression); + List parts = StringRoutines.separateString(macroPath, "#"); + if (parts.size()!=2) { + throw new TemplateProcessingException("Invalid macro path '" + macroPath + "'"); + } + + Template template = aLibrary.lookupTemplate((String) parts.get(0)); + Map definitions = (Map) template.getContext().get(MACRO_DEFINITIONS_KEY); + if (template==null) { + throw new TemplateProcessingException("Cannot find template '" + (String) parts.get(0) + "'"); + } + if (definitions==null || !definitions.containsKey(parts.get(1))) { + throw new TemplateProcessingException("No macro '"+(String) parts.get(1)+"' found in template '" + (String) parts.get(0) + "'"); + } + + MacroTemplateNode macro = (MacroTemplateNode) definitions.get(parts.get(1)); + + macro.process(aParser, aContext, aDestination, aLogger, aTemplateContext, aLibrary); + } + else { + aDestination.append(prefix); + + childNode.process(aParser, aContext, aDestination, aLogger, aTemplateContext, aLibrary); + aDestination.append(suffix); + } + } + + public String getPlainText() { + return childNode.getPlainText(); + } + } +} diff --git a/source/mir/generator/tal/template/PlainTextTemplateNode.java b/source/mir/generator/tal/template/PlainTextTemplateNode.java new file mode 100755 index 00000000..617d45d2 --- /dev/null +++ b/source/mir/generator/tal/template/PlainTextTemplateNode.java @@ -0,0 +1,77 @@ +/* + * 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.generator.tal.template; + +import java.util.Map; + +import mir.generator.tal.interfaces.TALExpressionParser; +import mir.generator.tal.interfaces.TALLogger; + +/** + * Simple TemplateNode that just outputs a fixed + * piece of allText. + */ +public class PlainTextTemplateNode implements TemplateNode { + private String allText; + private String plainText; + + public PlainTextTemplateNode() { + this("", ""); + } + + public PlainTextTemplateNode(String aText, String aPlainText) { + allText = aText; + plainText = aPlainText; + } + + /** Appends text at the end */ + public void appendText(String aText) { + allText = allText + aText; + } + + /** Appends allText at the end */ + public void appendPlainText(String aText) { + plainText = plainText + aText; + } + + public String getText() { + return allText; + } + + public String getPlainText() { + return plainText; + } + + public void process(TALExpressionParser aParser, Object aContext, + StringBuffer aDestination, TALLogger aLogger, + Map aTemplateContext, TemplateLibrary aLibrary) throws TemplateProcessingException { + aDestination.append(allText); + } +} diff --git a/source/mir/generator/tal/template/Template.java b/source/mir/generator/tal/template/Template.java new file mode 100755 index 00000000..e890c054 --- /dev/null +++ b/source/mir/generator/tal/template/Template.java @@ -0,0 +1,68 @@ +/* + * 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.generator.tal.template; + +import java.io.PrintWriter; +import java.util.Map; + +import mir.generator.tal.interfaces.TALExpressionParser; +import mir.generator.tal.interfaces.TALLogger; + +/** + * @see TAL Spec + */ + +public class Template { + private TemplateNode rootNode; + private TALExpressionParser parser; + private Map context; + + public Template(TALExpressionParser aParser, TemplateNode aRootNode, Map aTemplateContext) { + rootNode = aRootNode; + parser = aParser; + context = aTemplateContext; + } + + /** get this template's context */ + public Map getContext() { + return context; + } + + public void process(Object aContext, PrintWriter aDestination, + TALLogger aLogger, TemplateLibrary aLibrary) throws TemplateProcessingException { + StringBuffer output = new StringBuffer(); + + aLogger.debug("Template", "processing rootnode"); + rootNode.process(parser, aContext, output, aLogger, context, aLibrary); + aLogger.debug("Template", "done processing rootnode"); + aDestination.print(output); + } + +} \ No newline at end of file diff --git a/source/mir/generator/tal/template/TemplateLibrary.java b/source/mir/generator/tal/template/TemplateLibrary.java new file mode 100755 index 00000000..e558c890 --- /dev/null +++ b/source/mir/generator/tal/template/TemplateLibrary.java @@ -0,0 +1,41 @@ +/* + * 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.generator.tal.template; + +/** + * A TemplateLibrary offers access to a set of {@link Template}s. + * Templates can be looked up by name. + */ +public interface TemplateLibrary { + /** + * Looks up a Template based on a name + */ + public Template lookupTemplate(String aTemplateName) throws TemplateProcessingException; +} diff --git a/source/mir/generator/tal/template/TemplateNode.java b/source/mir/generator/tal/template/TemplateNode.java new file mode 100755 index 00000000..824552d1 --- /dev/null +++ b/source/mir/generator/tal/template/TemplateNode.java @@ -0,0 +1,52 @@ +/* + * 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.generator.tal.template; + +import java.util.Map; + +import mir.generator.tal.interfaces.TALExpressionParser; +import mir.generator.tal.interfaces.TALLogger; + +/** + * A {@link Template} consists of a chain of TemplateNodes. + */ +public interface TemplateNode { + /** + */ + public void process( + TALExpressionParser aParser, + Object aContext, + StringBuffer aDestination, + TALLogger aLogger, + Map aTemplateContext, + TemplateLibrary aTemplateLibrary) throws TemplateProcessingException; + + public String getPlainText(); +} diff --git a/source/mir/generator/tal/template/TemplateNodeLibrary.java b/source/mir/generator/tal/template/TemplateNodeLibrary.java new file mode 100755 index 00000000..bdb85459 --- /dev/null +++ b/source/mir/generator/tal/template/TemplateNodeLibrary.java @@ -0,0 +1,49 @@ +/* + * 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.generator.tal.template; + +import java.util.Map; + +import mir.util.xml.XMLName; +import mir.util.xml.XMLParserExc; +import mir.generator.tal.interfaces.TALExpressionParser; + +public interface TemplateNodeLibrary { + /** + * Construct a {@link TemplateNode} based on the tag and attributes given. + * + * @param anExpressionParser + * @param aTag + * @param anAttributes + * @param aChildTemplateNode + */ + public TemplateNode constructTemplateNode(TALExpressionParser anExpressionParser, + XMLName aTag, Map anAttributes, TemplateNode aChildTemplateNode, Map aTemplateContext) throws XMLParserExc; +} diff --git a/source/mir/generator/tal/template/TemplateNodeLibraryRegistry.java b/source/mir/generator/tal/template/TemplateNodeLibraryRegistry.java new file mode 100755 index 00000000..a67e371e --- /dev/null +++ b/source/mir/generator/tal/template/TemplateNodeLibraryRegistry.java @@ -0,0 +1,35 @@ +/* + * 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.generator.tal.template; + +public interface TemplateNodeLibraryRegistry { + public TemplateNodeLibrary findLibraryForUrl(String aUrl); + public TemplateNodeLibrary findLibraryForPrefix(String aPrefix); +} diff --git a/source/mir/generator/tal/template/TemplateProcessingException.java b/source/mir/generator/tal/template/TemplateProcessingException.java new file mode 100755 index 00000000..19a70b43 --- /dev/null +++ b/source/mir/generator/tal/template/TemplateProcessingException.java @@ -0,0 +1,52 @@ +/* + * 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.generator.tal.template; + +public class TemplateProcessingException extends Exception { + private Throwable cause; + + public TemplateProcessingException(Throwable aCause) { + this (aCause.getMessage(), aCause); + } + + public TemplateProcessingException(String aMessage, Throwable aCause) { + super(aMessage); + + cause = aCause; + } + + public TemplateProcessingException(String aMessage) { + this(aMessage, null); + } + + public Throwable getCause() { + return cause; + } +} diff --git a/source/mir/log/Logger.java b/source/mir/log/Logger.java index 47dc7db9..46d052a2 100755 --- a/source/mir/log/Logger.java +++ b/source/mir/log/Logger.java @@ -18,13 +18,13 @@ * 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. + * 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. */ @@ -38,4 +38,6 @@ public interface Logger { public void warn( Object o, String s); public void error( Object o, String s); public void fatal( Object o, String s); + + public void reload() throws LoggerExc, LoggerFailure; } diff --git a/source/mir/log/Log.java b/source/mir/log/LoggerEngine.java similarity index 73% rename from source/mir/log/Log.java rename to source/mir/log/LoggerEngine.java index 17fec303..9073595c 100755 --- a/source/mir/log/Log.java +++ b/source/mir/log/LoggerEngine.java @@ -18,65 +18,64 @@ * 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. + * 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.log; import mir.config.MirPropertiesConfiguration; -import mir.config.MirPropertiesConfiguration.PropertiesConfigExc; -public class Log { - - private static Logger myLogger; +public class LoggerEngine { + private static Logger loggerInstance; static { try { String loggerClass = MirPropertiesConfiguration.instance().getString("Log.LogClass"); - myLogger = (Logger) Class.forName(loggerClass).newInstance(); + loggerInstance = (Logger) Class.forName(loggerClass).newInstance(); } catch (java.lang.ClassNotFoundException cnfe) { - System.err.println("Log was not able to initialize: class not found"); + System.err.println("LoggerEngine was not able to initialize: class not found"); cnfe.printStackTrace(System.err); } catch (java.lang.InstantiationException ie) { System.err.println( - "Log was not able to initialize: could not initialize class"); + "LoggerEngine was not able to initialize: could not initialize class"); ie.printStackTrace(System.err); } catch (java.lang.IllegalAccessException iae) { - System.err.println("Log was not able to initialize: illegal access"); + System.err.println("LoggerEngine was not able to initialize: illegal access"); iae.printStackTrace(System.err); } - catch (PropertiesConfigExc e) { - e.printStackTrace(System.err); - } } public static void debug(Object o, String s) { - myLogger.debug(o, s); + loggerInstance.debug(o, s); } public static void info(Object o, String s) { - myLogger.info(o, s); + loggerInstance.info(o, s); } public static void warn(Object o, String s) { - myLogger.warn(o, s); + loggerInstance.warn(o, s); } public static void error(Object o, String s) { - myLogger.error(o, s); + loggerInstance.error(o, s); } public static void fatal(Object o, String s) { - myLogger.fatal(o, s); + loggerInstance.fatal(o, s); + } + + public static void reload() throws LoggerExc, LoggerFailure { + loggerInstance.reload(); } } diff --git a/source/mir/log/TestFramework.java b/source/mir/log/LoggerExc.java similarity index 80% rename from source/mir/log/TestFramework.java rename to source/mir/log/LoggerExc.java index 48a7891d..10bfd70b 100755 --- a/source/mir/log/TestFramework.java +++ b/source/mir/log/LoggerExc.java @@ -18,26 +18,21 @@ * 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. + * 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.log; +import multex.Exc; -public class TestFramework { - - public static void main(String[] args) { - TestFramework t = new TestFramework(); - - Log.info( TestFramework.class, "class"); - Log.info( t, "object" ); - Log.info( null, "lalala" ); +public class LoggerExc extends Exc { + public LoggerExc(String aMessage) { + super(aMessage); } } diff --git a/source/mir/log/LoggerFailure.java b/source/mir/log/LoggerFailure.java new file mode 100755 index 00000000..f8d1b16c --- /dev/null +++ b/source/mir/log/LoggerFailure.java @@ -0,0 +1,43 @@ +/* + * 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.log; + +import multex.Failure; + +public class LoggerFailure extends Failure { + + public LoggerFailure(String aMessage,Throwable aCause) { + super(aMessage, aCause); + } + + public LoggerFailure(Throwable aCause) { + this (aCause.getMessage(), aCause); + } +} diff --git a/source/mir/log/LoggerWrapper.java b/source/mir/log/LoggerWrapper.java index 7853ef98..eb8db650 100755 --- a/source/mir/log/LoggerWrapper.java +++ b/source/mir/log/LoggerWrapper.java @@ -18,13 +18,13 @@ * 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. + * 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. */ @@ -45,23 +45,23 @@ public class LoggerWrapper { } public void debug( String aMessage ) { - Log.debug(object, aMessage); + LoggerEngine.debug(object, aMessage); }; public void info( String aMessage ) { - Log.info(object, aMessage); + LoggerEngine.info(object, aMessage); }; public void warn( String aMessage ) { - Log.warn(object, aMessage); + LoggerEngine.warn(object, aMessage); }; public void error( String aMessage ) { - Log.error(object, aMessage); + LoggerEngine.error(object, aMessage); }; public void fatal( String aMessage ) { - Log.fatal(object, aMessage); + LoggerEngine.fatal(object, aMessage); }; public void message( int aType, String aMessage) { diff --git a/source/mir/log/log4j/LoggerImpl.java b/source/mir/log/log4j/LoggerImpl.java index 99ebed48..cd80fd83 100755 --- a/source/mir/log/log4j/LoggerImpl.java +++ b/source/mir/log/log4j/LoggerImpl.java @@ -18,13 +18,13 @@ * 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. + * 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.log.log4j; @@ -33,8 +33,8 @@ import java.util.HashMap; import java.util.Map; import mir.config.MirPropertiesConfiguration; -import mir.config.MirPropertiesConfiguration.PropertiesConfigExc; - +import mir.log.LoggerExc; +import mir.log.LoggerFailure; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; @@ -42,33 +42,53 @@ import org.apache.log4j.PropertyConfigurator; public class LoggerImpl implements mir.log.Logger { private static Map loggers = new HashMap(); - public LoggerImpl() throws PropertiesConfigExc { - System.setProperty("log.home", - MirPropertiesConfiguration.instance().getStringWithHome("Log.Home")); - PropertyConfigurator.configure( - MirPropertiesConfiguration.instance().getStringWithHome("Log.log4j.ConfigurationFile").trim()); + public LoggerImpl() throws LoggerExc { + reload(); } + /** {@inheritDoc} */ public void debug(Object o, String s) { this.getLogger(o).debug(s); } + /** {@inheritDoc} */ public void info(Object o, String s) { this.getLogger(o).info(s); } + /** {@inheritDoc} */ public void warn(Object o, String s) { this.getLogger(o).warn(s); } + /** {@inheritDoc} */ public void error(Object o, String s) { this.getLogger(o).error(s); } + /** {@inheritDoc} */ public void fatal(Object o, String s) { this.getLogger(o).fatal(s); } + /** {@inheritDoc} */ + public void reload() throws LoggerExc, LoggerFailure { + try { + synchronized (loggers) { + System.setProperty("log.home", + MirPropertiesConfiguration.instance().getFile("Log.Home").getAbsolutePath()); + + PropertyConfigurator.configure( + MirPropertiesConfiguration.instance().getFile("Log.log4j.ConfigurationFile").getAbsolutePath()); + + loggers.clear(); + } + } + catch (Throwable t) { + throw new LoggerFailure(t); + } + } + private Logger getLogger(Object o) { String name; Logger l; diff --git a/source/mir/media/MirMedia.java b/source/mir/media/MediaHandler.java similarity index 68% rename from source/mir/media/MirMedia.java rename to source/mir/media/MediaHandler.java index 40f21a1d..0283649a 100755 --- a/source/mir/media/MirMedia.java +++ b/source/mir/media/MediaHandler.java @@ -29,10 +29,12 @@ */ package mir.media; -import java.io.InputStream; -import java.util.List; - +import java.io.InputStream; +import java.io.File; +import java.util.List; + import mir.entity.Entity; +import mir.session.UploadedFile; /** * Interface for Media handling in Mir. All media handlers @@ -79,57 +81,48 @@ import mir.entity.Entity; * ) and just override the things that need to be specific. see MediaHandlerAudio * * @author , the Mir-coders group - * @version $Id: MirMedia.java,v 1.19 2003/09/03 18:29:01 zapata Exp $ */ -public interface MirMedia{ +public interface MediaHandler { + /** + * Store the media content from an {@link UploadedFile} + */ + public void store(UploadedFile anUploadedFile, Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure; + + /** + * Store the media content from an input stream. + */ + public void store(InputStream anInputStream, Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure; /** - * Takes the uploaded media data itself, along with the media Entity - * which contains the Media metadata plus the MediaType entity containing - * all the info for the specific media type itself. It's job is store the - * Media data (content) itself, this could be on the local filesystem, in the - * DB or even on a remote host. It then inserts the MetaData in the DB. - * @param InputStream, a stream of the uploaded data. - * @param ent, an Entity holding the media MetaData - * @param mediaType, an Entity holding the media_table entry - * @return boolean, success/fail - * @see mir.entity.Entity + * Store the media content from a file. */ - public abstract void set (InputStream in, Entity ent, Entity mediaTypeEnt ) throws MediaExc, MediaFailure; + public void store(File aFile, Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure; - public abstract void produce (Entity ent, Entity mediaTypeEnt ) throws MediaExc, MediaFailure; + /** + * Perform production related tasks for this media. + */ + public void produce(Entity aMedia, Entity aMediaType ) throws MediaExc, MediaFailure; /** * Get's the media data from storage and returns it as an InputStream * Not very useful for most media types as they are stored in a file, * but very usefull for ones stored in the DB as it is necessary to get * it first before making a file out of it (in Producer*). - * @param ent, an Entity holding the media MetaData - * @param mediaType, an Entity holding the media_table entry - * @return java.io.InputStream - * @see mir.entity.Entity */ - public abstract InputStream getMedia (Entity ent, Entity mediaTypeEnt) throws MediaExc, MediaFailure; + public InputStream getMedia (Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure; /** * Pretty much like get() above. But get's the specific Icon * representation. useful for media stored in the DB. - * @param ent, an Entity holding the media MetaData - * @return java.io.InputStream - * @see mir.entity.Entity */ - public abstract InputStream getIcon (Entity ent) throws MediaExc, MediaFailure; + public InputStream getThumbnail(Entity aMedia) throws MediaExc, MediaFailure; /** - * - * @param ent - * @return - * @throws MediaExc - * @throws MediaFailure + * Returns the mime-type of the media's thumbnail */ - public abstract String getIconMimeType (Entity aMediaEntity, Entity aMediaType) throws MediaExc, MediaFailure; + public String getThumbnailMimeType(Entity aMediaEntity, Entity aMediaType) throws MediaExc, MediaFailure; /** * gets the final content representation for the media @@ -138,23 +131,16 @@ public interface MirMedia{ * streaming link, etc..) * It should use the helper functions in the StringUtil class to * build URL's safely, eliminating any *illegal* user input. - * @param ent, an Entity holding the media MetaData - * @param mediaTypeEnt, an Entity holding the media_table entry - * @return String, the url. - * @see mir.entity.Entity - * @see mir.misc.StringUtil */ - public abstract List getURL (Entity ent, Entity mediaTypeEnt) throws MediaExc, MediaFailure; + public List getURL (Entity aMedia, Entity aMediaType) throws MediaExc, MediaFailure; /** * Returns the absolute filesystem path to where the media * content should be stored. This path is usually defined * in the configuration wich is accessible through the MirConfig * class. - * @return String, the path. - * @see mir.misc.MirConfig */ - public abstract String getStoragePath () throws MediaExc, MediaFailure; + public String getStoragePath () throws MediaExc, MediaFailure; /** * Returns the *relative* filesystem path to where the media @@ -163,10 +149,8 @@ public interface MirMedia{ * This path is usually defined * in the configuration wich is accessible through the MirConfig * class. - * @return String, the path. - * @see mir.misc.MirConfig */ - public abstract String getIconStoragePath () throws MediaExc, MediaFailure; + public String getIconStoragePath () throws MediaExc, MediaFailure; /** * Returns the base URL to that the media is accessible from @@ -176,10 +160,8 @@ public interface MirMedia{ * It is usually defined * in the configuration witch is accessible through the MirConfig * class. - * @return String, the base URL to the host. - * @see mir.misc.MirConfig */ - public abstract String getPublishHost () throws MediaExc, MediaFailure; + public String getPublishHost () throws MediaExc, MediaFailure; /** * Returns the file name of the Icon representing the media type. @@ -187,10 +169,8 @@ public interface MirMedia{ * It is usually defined * in the configuration wich is accessible through the MirConfig * class. - * @return String, the icon filename. - * @see mir.misc.MirConfig */ - public abstract String getBigIconName (); + public String getBigIconName (); /** * Returns the file name of the small Icon representing @@ -199,42 +179,22 @@ public interface MirMedia{ * It is usually defined * in the configuration wich is accessible through the MirConfig * class. - * @return String, the icon filename. - * @see mir.misc.MirConfig */ - public abstract String getTinyIconName (); + public String getTinyIconName (); - /** + /** * Returns the IMG SRC "ALT" text to be used * for the Icon representations * @return String, the ALT text. */ - public abstract String getIconAltName (); - - /** - * your can all figure it out. - * @return boolean. - */ - public abstract boolean isVideo (); - - /** - * you can all figure it out. - * @return boolean. - */ - public abstract boolean isAudio (); - - /** - * you can all figure it out. - * @return boolean. - */ - public abstract boolean isImage (); + public String getIconAltName (); /** * returns a brief text dscription of what this * media type is. * @return String */ - public abstract String getDescr (Entity mediaTypeEnt); + public String getDescr (Entity aMediaType); } diff --git a/source/mir/misc/FileUtil.java b/source/mir/misc/FileUtil.java index 3f08a573..688d9514 100755 --- a/source/mir/misc/FileUtil.java +++ b/source/mir/misc/FileUtil.java @@ -18,17 +18,20 @@ * 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. + * 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; @@ -36,32 +39,12 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.Reader; - -import mir.config.MirPropertiesConfiguration; -import mir.config.MirPropertiesConfiguration.PropertiesConfigExc; - /** * Hilfsklasse zum Mergen von Template und Daten */ public final class FileUtil { - - private static String producerStorageRoot; - - // - // Initialisierung - - static { - try { - producerStorageRoot = - MirPropertiesConfiguration.instance().getString("Producer.StorageRoot"); - } - catch (PropertiesConfigExc e) { - e.printStackTrace(); - } - } - /** - * Privater Konstruktor, um versehentliche Instantiierung zu verhindern + * Privater Construktor to avoid accidental instantiation */ private FileUtil() { } @@ -88,8 +71,9 @@ public final class FileUtil { if (in != null) { try { - FileOutputStream out = new FileOutputStream(f); + 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) { @@ -131,7 +115,7 @@ public final class FileUtil { try { File f = getFile(filename); FileOutputStream fOut = new FileOutputStream(f); - OutputStreamWriter out = new OutputStreamWriter(fOut, encoding); + BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fOut, encoding),8192); int read; char[] cbuf = new char[8 * 1024]; while ( (read = in.read(cbuf)) != -1) { @@ -158,8 +142,8 @@ public final class FileUtil { try { if (out.length != f.length()) return false; - FileInputStream inStream; - inStream = new FileInputStream(f); + BufferedInputStream inStream; + inStream = new BufferedInputStream(new FileInputStream(f),8192); inStream.read(out); inStream.close(); } diff --git a/source/mir/misc/LineFilterWriter.java b/source/mir/misc/LineFilterWriter.java deleted file mode 100755 index 240a14ec..00000000 --- a/source/mir/misc/LineFilterWriter.java +++ /dev/null @@ -1,96 +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.IOException; -import java.io.PrintWriter; -import java.io.Writer; - -/** - * LineFilterWriter eliminates superfluous \t \r \n and spaces - * and thus compresses the output of html - * - **/ -public final class LineFilterWriter extends PrintWriter{ - - protected Writer out; - - public LineFilterWriter(Writer out) { - super(out); - this.out=out; - } - - public final void write(String str){ - int i,j,len; - boolean state=true; - char c; - len=str.length(); - if (len==1) {try{out.write(str);}catch(IOException e){}return;} - StringBuffer sbuf = new StringBuffer(); - - for(i=0;i\r?\n
){1,}"); - re_mail = new RE("\\b([a-zA-Z0-9_.-]+)@([a-zA-Z0-9_-]+)\\.([a-zA-Z0-9_.-]+)\\b"); - re_url = new RE("((https://)|(http://)|(ftp://)){1}([a-zA-Z0-9_-]+).([a-zA-Z0-9_.:-]+)/?([^ \t\r\n<>\\)\\]]+[^ \t\r\n.,<>\\)\\]])"); - re_tags = new RE("<[^>]*>",RE.REG_ICASE); - re_tables = new RE("<[ \t\r\n/]*(table|td|tr)[ \t\r\n]*>",RE.REG_ICASE); - re_forbiddenTags = new RE("<[ \t\r\n/]*(html|meta|body|head|script)[ \t\r\n]*>",RE.REG_ICASE); - } - catch (REException e){ - System.err.println("FATAL: StringUtil: could not precompile REGEX: "+e.toString()); - } - } - - /** - * Formats a number with the specified minimum and maximum number of digits. - **/ - public static synchronized String zeroPaddingNumber(long value, int minDigits, - int maxDigits) - { - NumberFormat numberFormat = NumberFormat.getInstance(); - numberFormat.setMinimumIntegerDigits(minDigits); - numberFormat.setMaximumIntegerDigits(maxDigits); - return numberFormat.format(value); - } - - /** - * Wandelt Datum in einen 8-ziffrigen String um (yyyymmdd) - * @param theDate - * @return 8-ziffriger String (yyyymmdd) - */ - - public static final String date2webdbDate (GregorianCalendar theDate) { - StringBuffer webdbDate = new StringBuffer(); - webdbDate.append(String.valueOf(theDate.get(Calendar.YEAR))); - webdbDate.append(pad2(theDate.get(Calendar.MONTH) + 1)); - webdbDate.append(pad2(theDate.get(Calendar.DATE))); - return webdbDate.toString(); - } - - /** - * Wandelt Calendar in einen 12-ziffrigen String um (yyyymmddhhmm) - * @param theDate - * @return 12-ziffriger String (yyyymmdd) - */ - - public static final String date2webdbDateTime (GregorianCalendar theDate) { - StringBuffer webdbDate = new StringBuffer(); - webdbDate.append(String.valueOf(theDate.get(Calendar.YEAR))); - webdbDate.append(pad2(theDate.get(Calendar.MONTH) + 1)); - webdbDate.append(pad2(theDate.get(Calendar.DATE))); - webdbDate.append(pad2(theDate.get(Calendar.HOUR))); - webdbDate.append(pad2(theDate.get(Calendar.MINUTE))); - return webdbDate.toString(); - } - - /** - * Return a http://www.w3.org/TR/NOTE-datetime formatted date (yyyy-mm-ddThh:mm:ssTZ) - * @param theDate - * @return w3approved datetime - */ - - public static final String date2w3DateTime (GregorianCalendar theDate) { - StringBuffer webdbDate = new StringBuffer(); - webdbDate.append(String.valueOf(theDate.get(Calendar.YEAR))); - webdbDate.append("-"); - webdbDate.append(pad2(theDate.get(Calendar.MONTH) + 1)); - webdbDate.append("-"); - webdbDate.append(pad2(theDate.get(Calendar.DATE))); - webdbDate.append("T"); - webdbDate.append(pad2(theDate.get(Calendar.HOUR_OF_DAY))); - webdbDate.append(":"); - webdbDate.append(pad2(theDate.get(Calendar.MINUTE))); - webdbDate.append(":"); - webdbDate.append(pad2(theDate.get(Calendar.SECOND))); - //assumes you are an hour-multiple away from UTC.... - int offset=(theDate.get(Calendar.ZONE_OFFSET)/(60*60*1000)); - if (offset < 0){ - webdbDate.append("-"); - } - else{ - webdbDate.append("+"); - } - webdbDate.append(pad2(Math.abs(offset))); - webdbDate.append(":00"); - return webdbDate.toString(); - } - - /** - * wandelt Calendar in dd.mm.yyyy / hh.mm um - * @param theDate - * @return String mit (dd.mm.yyyy / hh.mm um) - */ - public static String date2readableDateTime (GregorianCalendar theDate) { - String readable = ""; - int hour; - readable += pad2(theDate.get(Calendar.DATE)); - readable += "." + pad2(theDate.get(Calendar.MONTH) + 1); - readable += "." + String.valueOf(theDate.get(Calendar.YEAR)); - hour = theDate.get(Calendar.HOUR); - if (theDate.get(Calendar.AM_PM) == Calendar.PM) - hour += 12; - readable += " / " + pad2(hour); - readable += ":" + pad2(theDate.get(Calendar.MINUTE)); - return readable; - } - - /** - * deleteForbiddenTags - * this method deletes all