From 8297c34c7a424107fd7d1980b6e8e5a3ae26494b Mon Sep 17 00:00:00 2001 From: zapata Date: Wed, 3 Sep 2003 17:49:37 +0000 Subject: [PATCH] major cleanup: - freemarker dependencies isolated in 1 or 2 files - all servlets use the generator infrastructure - removed lots of dead wood - misc. small fixes here and there --- bundles/admin_en.properties | 9 +- source/Mir.java | 140 +- source/default.properties | 84 +- source/mir/entity/Entity.java | 36 +- source/mir/entity/EntityList.java | 575 ++-- source/mir/entity/EntityRelation.java | 124 - .../entity/adapter/EntityAdapterDefinition.java | 19 +- source/mir/entity/adapter/EntityListAdapter.java | 237 +- source/mir/generator/FreemarkerGenerator.java | 1 - source/mir/media/MirMedia.java | 10 +- source/mir/misc/HTMLTemplateProcessor.java | 399 --- source/mir/module/AbstractModule.java | 31 +- .../mir/producer/EntityBatchingProducerNode.java | 33 +- .../reader/DefaultProducerNodeBuilders.java | 2 - source/mir/rss/RDFResource.java | 3 +- source/mir/servlet/AbstractServlet.java | 549 ++-- source/mir/servlet/ServletModule.java | 532 ++-- source/mir/servlet/ServletModuleDispatch.java | 60 +- source/mir/servlet/ServletModuleShow.java | 103 - source/mir/storage/Database.java | 3060 ++++++++++---------- source/mir/storage/StorageObject.java | 28 +- source/mir/util/DateTimeFunctions.java | 6 +- source/mir/util/HTTPParsedRequest.java | 2 +- source/mir/util/PropertiesManipulator.java | 15 +- source/mircoders/entity/EntityContent.java | 134 +- source/mircoders/entity/EntityMedia.java | 75 - source/mircoders/entity/EntityUploadedMedia.java | 421 ++- .../basic/MirBasicAdminInterfaceLocalizer.java | 27 + .../basic/MirBasicChildArticlePostingHandler.java | 117 +- .../basic/MirBasicDataModelLocalizer.java | 1243 ++++---- source/mircoders/media/MediaHandlerGeneric.java | 34 +- source/mircoders/media/MediaHandlerImages.java | 8 +- source/mircoders/media/MediaHandlerMp3.java | 284 +- source/mircoders/media/MediaHandlerRealAudio.java | 258 +- source/mircoders/media/MediaHandlerRealVideo.java | 258 +- source/mircoders/module/ModuleArticleType.java | 10 +- source/mircoders/module/ModuleComment.java | 41 +- source/mircoders/module/ModuleMediaType.java | 18 +- source/mircoders/module/ModuleMediafolder.java | 30 +- source/mircoders/module/ModuleTopics.java | 17 - source/mircoders/pdf/PDFGenerator.java | 13 +- .../producer/ContentModifyingProducerNode.java | 16 +- .../producer/PDFPreFormattingProducerNode.java | 460 +-- source/mircoders/servlet/ServletHelper.java | 358 +-- source/mircoders/servlet/ServletModuleAdmin.java | 172 +- .../servlet/ServletModuleArticleType.java | 120 +- source/mircoders/servlet/ServletModuleAudio.java | 15 +- .../mircoders/servlet/ServletModuleBreaking.java | 176 +- source/mircoders/servlet/ServletModuleComment.java | 22 +- .../servlet/ServletModuleCommentStatus.java | 26 +- source/mircoders/servlet/ServletModuleContent.java | 44 +- .../mircoders/servlet/ServletModuleFileEdit.java | 10 +- source/mircoders/servlet/ServletModuleHidden.java | 35 +- source/mircoders/servlet/ServletModuleImages.java | 11 +- .../mircoders/servlet/ServletModuleLanguage.java | 23 +- .../servlet/ServletModuleMediafolder.java | 151 +- source/mircoders/servlet/ServletModuleMessage.java | 192 +- .../mircoders/servlet/ServletModuleOpenIndy.java | 6 +- .../mircoders/servlet/ServletModuleOtherMedia.java | 9 +- source/mircoders/servlet/ServletModuleTopics.java | 36 +- .../servlet/ServletModuleUploadedMedia.java | 29 +- source/mircoders/servlet/ServletModuleUsers.java | 717 +++-- source/mircoders/servlet/ServletModuleVideo.java | 28 +- source/mircoders/storage/DatabaseArticleType.java | 15 +- source/mircoders/storage/DatabaseAudio.java | 174 +- source/mircoders/storage/DatabaseComment.java | 19 +- .../mircoders/storage/DatabaseCommentStatus.java | 11 +- .../mircoders/storage/DatabaseCommentToMedia.java | 51 +- source/mircoders/storage/DatabaseContent.java | 18 +- .../mircoders/storage/DatabaseContentToMedia.java | 51 +- .../mircoders/storage/DatabaseContentToTopics.java | 30 +- source/mircoders/storage/DatabaseImageColor.java | 10 +- source/mircoders/storage/DatabaseImageFormat.java | 12 +- source/mircoders/storage/DatabaseImageLayout.java | 12 +- source/mircoders/storage/DatabaseImageType.java | 132 +- source/mircoders/storage/DatabaseImages.java | 193 +- source/mircoders/storage/DatabaseLanguage.java | 172 +- source/mircoders/storage/DatabaseMedia.java | 91 - source/mircoders/storage/DatabaseMediaType.java | 4 - source/mircoders/storage/DatabaseMediafolder.java | 136 +- source/mircoders/storage/DatabaseOther.java | 195 +- source/mircoders/storage/DatabaseRights.java | 17 +- source/mircoders/storage/DatabaseTopics.java | 163 +- .../mircoders/storage/DatabaseUploadedMedia.java | 18 +- source/mircoders/storage/DatabaseUsers.java | 13 +- source/mircoders/storage/DatabaseVideo.java | 16 +- templates/admin/EDITFUNCTIONS.template | 17 +- templates/admin/FUNCTIONS.template | 79 +- templates/admin/FUNCTIONS_media.template | 161 +- templates/admin/abuse.log.template | 2 +- templates/admin/articletype.template | 64 +- templates/admin/articletypelist.template | 26 +- templates/admin/breaking.template | 82 +- templates/admin/breakinglist.template | 54 +- templates/admin/commentlist.template | 2 +- templates/admin/commentstatus.template | 57 +- templates/admin/commentstatuslist.template | 34 +- templates/admin/content.template | 4 +- templates/admin/contentlist.template | 4 +- templates/admin/error.template | 24 +- templates/admin/foot.template | 2 +- templates/admin/head.template | 2 +- templates/admin/head_nonavi.template | 2 +- templates/admin/hiddenlist.template | 4 +- templates/admin/language.template | 66 +- templates/admin/languagelist.template | 33 +- templates/admin/linksimcs.template | 74 - templates/admin/login.template | 4 +- templates/admin/mediafolder.template | 69 +- templates/admin/mediafolderlist.template | 61 +- templates/admin/message.template | 96 +- templates/admin/messagelist.template | 79 +- templates/admin/start_admin.template | 8 +- templates/admin/topic.template | 42 +- templates/admin/topiclist.template | 46 +- templates/admin/user.template | 2 +- 116 files changed, 6372 insertions(+), 8083 deletions(-) delete mode 100755 source/mir/entity/EntityRelation.java delete mode 100755 source/mir/misc/HTMLTemplateProcessor.java delete mode 100755 source/mir/servlet/ServletModuleShow.java delete mode 100755 source/mircoders/entity/EntityMedia.java delete mode 100755 source/mircoders/storage/DatabaseMedia.java delete mode 100755 templates/admin/linksimcs.template diff --git a/bundles/admin_en.properties b/bundles/admin_en.properties index 30d45e08..94ed8e7b 100755 --- a/bundles/admin_en.properties +++ b/bundles/admin_en.properties @@ -1,6 +1,6 @@ ########## admin ########## # language: english -# $Id: admin_en.properties,v 1.48.2.8 2003/07/21 07:01:14 zapata Exp $ +# $Id: admin_en.properties,v 1.48.2.9 2003/09/03 17:49:37 zapata Exp $ languagename=English @@ -94,6 +94,7 @@ other_medialist.htmltitle=Other media overview # breaking breaking.htmltitle=Breaking news breaking.textinfo=(max. 5 lines / 250 characters) +breaking.id = id breaking.text=text breaking.date=date @@ -249,6 +250,7 @@ contentlist.select=Select # language language.htmltitle=Language +language.id=Id language.name=Language language.code=Language code @@ -266,6 +268,7 @@ login.submit= OK # mediafolder mediafolder.htmltitle=mediafolder +mediafolder.id=id mediafolder.date=date mediafolder.name=name mediafolder.location=location @@ -277,6 +280,7 @@ mediafolderlist.htmltitle=media folder list # message message.htmltitle=messages +message.id=id message.date=date message.title=title message.creator=author @@ -334,7 +338,10 @@ start.superusermenu=super-user functions (use with care!) # topic + topic.htmltitle=topic + +topic.id=id topic.title=name topic.description=description topic.filename=filename diff --git a/source/Mir.java b/source/Mir.java index 328864f1..dbdc8b61 100755 --- a/source/Mir.java +++ b/source/Mir.java @@ -29,9 +29,8 @@ */ import java.io.IOException; -import java.io.PrintWriter; import java.lang.reflect.Method; -import java.util.GregorianCalendar; +import java.util.*; import java.util.HashMap; import java.util.Iterator; import java.util.List; @@ -46,22 +45,12 @@ import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.util.MessageResources; -import freemarker.template.SimpleHash; -import freemarker.template.SimpleList; -import freemarker.template.SimpleScalar; -import freemarker.template.TemplateModel; import mir.config.MirPropertiesConfiguration; -import mir.entity.adapter.EntityIteratorAdapter; -import mir.generator.FreemarkerGenerator; -import mir.log.LoggerWrapper; -import mir.misc.HTMLTemplateProcessor; -import mir.misc.StringUtil; import mir.servlet.AbstractServlet; import mir.servlet.ServletModule; import mir.servlet.ServletModuleDispatch; import mir.servlet.ServletModuleExc; import mir.servlet.ServletModuleUserExc; -import mir.util.CachingRewindableIterator; import mir.util.ExceptionFunctions; import mir.util.StringRoutines; import mircoders.entity.EntityUsers; @@ -69,8 +58,6 @@ import mircoders.global.MirGlobal; import mircoders.module.ModuleMessage; import mircoders.module.ModuleUsers; import mircoders.servlet.ServletHelper; -import mircoders.servlet.ServletModuleFileEdit; -import mircoders.servlet.ServletModuleLocalizer; import mircoders.storage.DatabaseUsers; @@ -80,7 +67,7 @@ import mircoders.storage.DatabaseUsers; * Mir.java - main servlet, that dispatches to servletmodules * * @author $Author: zapata $ - * @version $Id: Mir.java,v 1.49.2.5 2003/07/20 05:49:47 zapata Exp $ + * @version $Id: Mir.java,v 1.49.2.6 2003/09/03 17:49:38 zapata Exp $ * */ public class Mir extends AbstractServlet { @@ -91,7 +78,7 @@ public class Mir extends AbstractServlet { private static List loginLanguages = null; - protected TemplateModel getLoginLanguages() throws ServletException { + protected List getLoginLanguages() throws ServletException { synchronized (Mir.class) { try { if (loginLanguages == null) { @@ -127,7 +114,7 @@ public class Mir extends AbstractServlet { } } - return FreemarkerGenerator.makeAdapter(loginLanguages); + return loginLanguages; } catch (Throwable t) { throw new ServletException(t.getMessage()); @@ -212,30 +199,31 @@ public class Mir extends AbstractServlet { session.setAttribute("login.target", queryString); } - _sendLoginPage(aResponse, aRequest, aResponse.getWriter()); + _sendLoginPage(aResponse, aRequest); } else { String moduleName = aRequest.getParameter("module"); checkLanguage(session, aRequest); if ( ( (moduleName == null) || moduleName.equals(""))) { - _sendStartPage(aResponse, aRequest, aResponse.getWriter(), - userEntity); + moduleName="Admin"; } - else if (moduleName.equals("login")) { + + + if (moduleName.equals("login")) { String target = (String) session.getAttribute("login.target"); if (target != null) { ServletHelper.redirect(aResponse, target); } else { - _sendStartPage(aResponse, aRequest, aResponse.getWriter(), userEntity); + ServletHelper.redirect(aResponse, ""); } } else if (moduleName.equals("logout")) { - logger.info(userEntity.get("login") + " has logged out"); + logger.info(userEntity.getValue("login") + " has logged out"); session.invalidate(); - _sendLoginPage(aResponse, aRequest, aResponse.getWriter()); + _sendLoginPage(aResponse, aRequest); return; } else { @@ -250,10 +238,9 @@ public class Mir extends AbstractServlet { Throwable cause = ExceptionFunctions.traceCauseException(e); if (cause instanceof ServletModuleUserExc) - handleUserError(aRequest, aResponse, aResponse.getWriter(), - (ServletModuleUserExc) cause); + handleUserError(aRequest, aResponse, (ServletModuleUserExc) cause); else - handleError(aRequest, aResponse, aResponse.getWriter(), cause); + handleError(aRequest, aResponse, cause); } if (aRequest.getParameter("killsession")!=null) @@ -269,13 +256,13 @@ public class Mir extends AbstractServlet { } /** - * Private method getServletModuleForName returns ServletModule - * from Cache - * - * @param moduleName - * @return ServletModule + * caching routine to get a module for a module name * + * @param moduleName the module name + * @return the requested module + * @throws ServletModuleExc */ + private static ServletModule getServletModuleForName(String moduleName) throws ServletModuleExc { // Instance in Map ? if (!servletModuleInstanceHash.containsKey(moduleName)) { @@ -311,43 +298,33 @@ public class Mir extends AbstractServlet { } } - private void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse, - PrintWriter out, ServletModuleUserExc anException) { + private void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse, ServletModuleUserExc anException) { try { logger.info("user error: " + anException.getMessage()); - SimpleHash modelRoot = new SimpleHash(); + + Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale()}); + MessageResources messages = MessageResources.getMessageResources("bundles.admin"); - modelRoot.put("errorstring", - new SimpleScalar( - messages.getMessage(getLocale(aRequest), anException.getMessage(), anException.getParameters()) - )); - modelRoot.put("date", new SimpleScalar(StringUtil.date2readableDateTime(new GregorianCalendar()))); - HTMLTemplateProcessor.process( - aResponse, - MirPropertiesConfiguration.instance().getString("Mir.UserErrorTemplate"), - modelRoot, - null, - out, - getLocale(aRequest), - fallbackLocale); - out.close(); + responseData.put("errorstring", messages.getMessage(getLocale(aRequest), anException.getMessage(), anException.getParameters())); + responseData.put("date", new GregorianCalendar().getTime()); + + ServletHelper.generateResponse(aResponse.getWriter(), responseData, MirPropertiesConfiguration.instance().getString("Mir.UserErrorTemplate")); } catch (Throwable e) { logger.error("Error handling user error" + e.toString()); } } - private void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse,PrintWriter out, Throwable anException) { + private void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse, Throwable anException) { try { logger.error("error: " + anException); - SimpleHash modelRoot = new SimpleHash(); - modelRoot.put("errorstring", new SimpleScalar(anException.getMessage())); - modelRoot.put("date", new SimpleScalar(StringUtil.date2readableDateTime( - new GregorianCalendar()))); - HTMLTemplateProcessor.process( - aResponse,MirPropertiesConfiguration.instance().getString("Mir.ErrorTemplate"), - modelRoot,null,out, getLocale(aRequest), getFallbackLocale()); - out.close(); + + Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale()}); + + responseData.put("errorstring", anException.toString()); + responseData.put("date", new GregorianCalendar().getTime()); + + ServletHelper.generateResponse(aResponse.getWriter(), responseData, MirPropertiesConfiguration.instance().getString("Mir.ErrorTemplate")); } catch (Throwable e) { logger.error("Error handling error: " + e.toString()); @@ -355,54 +332,19 @@ public class Mir extends AbstractServlet { } // Redirect-methods - private void _sendLoginPage(HttpServletResponse aResponse, HttpServletRequest aRequest, - PrintWriter out) { + private void _sendLoginPage(HttpServletResponse aResponse, HttpServletRequest aRequest) { String loginTemplate = configuration.getString("Mir.LoginTemplate"); - String sessionUrl = aResponse.encodeURL(""); try { - SimpleHash mergeData = new SimpleHash(); - SimpleList languages = new SimpleList(); - - mergeData.put("session", sessionUrl); + Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale()}); - mergeData.put("defaultlanguage", getDefaultLanguage(aRequest)); - mergeData.put("languages", getLoginLanguages()); + responseData.put("defaultlanguage", getDefaultLanguage(aRequest)); + responseData.put("languages", getLoginLanguages()); - HTMLTemplateProcessor.process(aResponse, loginTemplate, mergeData, null, out, getLocale(aRequest), getFallbackLocale()); + ServletHelper.generateResponse(aResponse.getWriter(), responseData, loginTemplate); } catch (Throwable e) { - handleError(aRequest, aResponse, out, e); - } - } - - private void _sendStartPage(HttpServletResponse aResponse, HttpServletRequest aRequest, - PrintWriter out, EntityUsers userEntity) { - String startTemplate = configuration.getString("Mir.StartTemplate"); - String sessionUrl = aResponse.encodeURL(""); - - try { - Map mergeData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale()}, "bundles.admin", "bundles.adminlocal"); - mergeData.put("messages", - new CachingRewindableIterator( - new EntityIteratorAdapter( "", "webdb_create desc", 10, - MirGlobal.localizer().dataModel().adapterModel(), "internalMessage", 10, 0))); - - mergeData.put("fileeditentries", ((ServletModuleFileEdit) ServletModuleFileEdit.getInstance()).getEntries()); - mergeData.put("administeroperations", ((ServletModuleLocalizer) ServletModuleLocalizer.getInstance()).getAdministerOperations()); - - mergeData.put("searchvalue", null); - mergeData.put("searchfield", null); - mergeData.put("searchispublished", null); - mergeData.put("searcharticletype", null); - mergeData.put("searchorder", null); - mergeData.put("selectarticleurl", null); - - ServletHelper.generateResponse(out, mergeData, startTemplate); - } - catch (Exception e) { - e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); - handleError(aRequest, aResponse, out, e); + handleError(aRequest, aResponse, e); } } diff --git a/source/default.properties b/source/default.properties index 78faf9e9..66aea54c 100755 --- a/source/default.properties +++ b/source/default.properties @@ -438,88 +438,74 @@ Mir.StartTemplate=start_admin.template Mir.ErrorTemplate=error.template Mir.UserErrorTemplate=usererror.template -ServletModule.Themen.ConfirmTemplate=confirm.template -ServletModule.Themen.ObjektTemplate=topic.template -ServletModule.Themen.ListTemplate=topiclist.template +ServletModule.Default.ListSize = 30 -ServletModule.LinksImcs.ConfirmTemplate=confirm.template -ServletModule.LinksImcs.ObjektTemplate=linksimcs.template -ServletModule.LinksImcs.ListTemplate=linksimcslist.template +ServletModule.Topics.DeleteConfirmationTemplate=confirm.template +ServletModule.Topics.EditTemplate=topic.template +ServletModule.Topics.ListTemplate=topiclist.template -ServletModule.Users.ConfirmTemplate=confirm.template -ServletModule.Users.ObjektTemplate=user.template +ServletModule.Users.DeleteConfirmationTemplate=confirm.template +ServletModule.Users.EditTemplate=user.template ServletModule.Users.ListTemplate=userlist.template -ServletModule.Images.ConfirmTemplate=confirm.template -ServletModule.Images.ObjektTemplate=image.template +ServletModule.Images.DeleteConfirmationTemplate=confirm.template +ServletModule.Images.EditTemplate=image.template ServletModule.Images.ListTemplate=imagelist.template -ServletModule.Audio.ConfirmTemplate=confirm.template -ServletModule.Audio.ObjektTemplate=audio.template +ServletModule.Audio.DeleteConfirmationTemplate=confirm.template +ServletModule.Audio.EditTemplate=audio.template ServletModule.Audio.ListTemplate=audiolist.template -ServletModule.Video.ConfirmTemplate=confirm.template -ServletModule.Video.ObjektTemplate=video.template +ServletModule.Video.DeleteConfirmationTemplate=confirm.template +ServletModule.Video.EditTemplate=video.template ServletModule.Video.ListTemplate=videolist.template -ServletModule.OtherMedia.ConfirmTemplate=confirm.template -ServletModule.OtherMedia.ObjektTemplate=other.template +ServletModule.OtherMedia.DeleteConfirmationTemplate=confirm.template +ServletModule.OtherMedia.EditTemplate=other.template ServletModule.OtherMedia.ListTemplate=medialist.template -ServletModule.Content.ConfirmTemplate=confirm.template -ServletModule.Content.ObjektTemplate=content.template +ServletModule.Content.DeleteConfirmationTemplate=confirm.template +ServletModule.Content.EditTemplate=content.template ServletModule.Content.ListTemplate=contentlist.template -ServletModule.Mediafolder.ConfirmTemplate=confirm.template -ServletModule.Mediafolder.ObjektTemplate=mediafolder.template +ServletModule.Mediafolder.DeleteConfirmationTemplate=confirm.template +ServletModule.Mediafolder.EditTemplate=mediafolder.template ServletModule.Mediafolder.ListTemplate=mediafolderlist.template -# -# config for ServletModuleComment - browsing/editing/deleting comments -ServletModule.Comment.ConfirmTemplate=confirm.template -ServletModule.Comment.ObjektTemplate=comment.template +ServletModule.Comment.DeleteConfirmationTemplate=confirm.template +ServletModule.Comment.EditTemplate=comment.template ServletModule.Comment.ListTemplate=commentlist.template -# -# config for ServletModuleHidden - lists all hidden articles of one month ServletModule.Hidden.ListTemplate=hiddenlist.template -# -# config for Breaking - browsing/editing/deleting breaking news -ServletModule.Breaking.ConfirmTemplate=confirm.template -ServletModule.Breaking.ObjektTemplate=breaking.template +ServletModule.Breaking.DeleteConfirmationTemplate=confirm.template +ServletModule.Breaking.EditTemplate=breaking.template ServletModule.Breaking.ListTemplate=breakinglist.template -# -# config for Breaking - editing text files -ServletModule.FileEdit.ConfirmTemplate=confirm.template -ServletModule.FileEdit.ObjektTemplate=fileedit.template +ServletModule.FileEdit.DeleteConfirmationTemplate=confirm.template +ServletModule.FileEdit.EditTemplate=fileedit.template ServletModule.FileEdit.ListTemplate=fileeditlist.template -# -# config for messages - browsing/editing/deleting internal messages -ServletModule.Messages.ConfirmTemplate=confirm.template -ServletModule.Messages.ObjektTemplate=message.template -ServletModule.Messages.ListTemplate=messagelist.template +ServletModule.Message.DeleteConfirmationTemplate=confirm.template +ServletModule.Message.EditTemplate=message.template +ServletModule.Message.ListTemplate=messagelist.template -# -# config for languages - browsing/editing/deleting languages -ServletModule.Language.ConfirmTemplate=confirm.template -ServletModule.Language.ObjektTemplate=language.template +ServletModule.Language.DeleteConfirmationTemplate=confirm.template +ServletModule.Language.EditTemplate=language.template ServletModule.Language.ListTemplate=languagelist.template -# -# config for article type -ServletModule.ArticleType.ConfirmTemplate=confirm.template +ServletModule.ArticleType.DeleteConfirmationTemplate=confirm.template ServletModule.ArticleType.EditTemplate=articletype.template ServletModule.ArticleType.ListTemplate=articletypelist.template -# -# config for comment status -ServletModule.CommentStatus.ConfirmTemplate=confirm.template +ServletModule.CommentStatus.DeleteConfirmationTemplate=confirm.template ServletModule.CommentStatus.EditTemplate=commentstatus.template ServletModule.CommentStatus.ListTemplate=commentstatuslist.template + + + + # # config for abuse ServletModule.Abuse.EditFilter.Template = abuse.filter.template diff --git a/source/mir/entity/Entity.java b/source/mir/entity/Entity.java index 54317b60..306c6fb5 100755 --- a/source/mir/entity/Entity.java +++ b/source/mir/entity/Entity.java @@ -40,23 +40,17 @@ import mir.misc.StringUtil; import mir.storage.StorageObject; import mir.storage.StorageObjectExc; import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleScalar; -import freemarker.template.TemplateHashModel; -import freemarker.template.TemplateModel; -import freemarker.template.TemplateModelException; -import freemarker.template.TemplateModelRoot; /** * Base class the entities are derived from. Provides base functionality of * an entity. Entities are used to represent rows of a database table.

- * Interfacing TemplateHashModel and TemplateModelRoot to be freemarker compliant * - * @version $Id: Entity.java,v 1.21.2.3 2003/05/24 15:33:11 zapata Exp $ + * @version $Id: Entity.java,v 1.21.2.4 2003/09/03 17:49:38 zapata Exp $ * @author rk * */ -public class Entity implements TemplateHashModel, TemplateModelRoot +public class Entity { protected static MirPropertiesConfiguration configuration; @@ -259,31 +253,5 @@ public class Entity implements TemplateHashModel, TemplateModelRoot throw new StorageObjectFailure("Storage Object Exception in entity", e); } - - // Now implements freemarkers TemplateHashModel - // two methods have to be overridden: - // 1. public boolean isEmpty() throws TemplateModelException - // 2. public TemplateModel get(java.lang.String key) throws TemplateModelException - - public boolean isEmpty() throws TemplateModelException { - return false; - } - - public TemplateModel get(java.lang.String key) throws TemplateModelException { - return new SimpleScalar(getValue(key)); - } - - public void put(java.lang.String key, TemplateModel model) { - // putting should only take place via setValue and is limited to the - // database fields associated with the entity. no additional freemarker - // stuff will be available via Entity. - logger.warn("put is called on entity! - the values will be lost!"); - } - - public void remove(java.lang.String key) { - logger.warn("remove is called on entity!"); - } - - ////////////////////////////////////////////////////////////////////////////////// } diff --git a/source/mir/entity/EntityList.java b/source/mir/entity/EntityList.java index c2616f18..f7924137 100755 --- a/source/mir/entity/EntityList.java +++ b/source/mir/entity/EntityList.java @@ -1,308 +1,267 @@ -/* - * 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; -import freemarker.template.TemplateListModel; -import freemarker.template.TemplateModel; - -/** - * - * Container class for lists of Entities. - * Now implements freemarker.template.TemplateListModel - * and @see mir.storage.store.StorableObject. - * - * @author - * first version 27.6.1999 - * - * @version 1.0 (freemarker compliant & and storable in ObjectStore) - */ -public class EntityList implements TemplateListModel, 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; - private int freemarkerListPointer=-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); - } - - -// The following methods have to be implemented -// for this class to be an implementation of the -// TemplateListModel of the Freemarker packages - - public TemplateModel get(int i) { return elementAt(i); } - public boolean isRewound() { return (freemarkerListPointer==-1) ? true : false; } - public void rewind() { freemarkerListPointer=-1; } - - public TemplateModel next() { - if (hasNext()) { - freemarkerListPointer++;return get(freemarkerListPointer); } - else return null; - } - - - /** - * Returns whether there is a next element - * @return true if there is a next element, else false - */ - - public boolean hasNext() { - return theEntityArrayList.size()>0 && freemarkerListPointer+2<=theEntityArrayList.size(); - } - - - /** - * Returns whether EntityList is empty or not - * @return true in case of empty list, false otherwise - */ - - public boolean isEmpty() { - if (theEntityArrayList!=null) - return theEntityArrayList.size()<1 ; - else return false; - } - - -// 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; + 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; + } + +} diff --git a/source/mir/entity/EntityRelation.java b/source/mir/entity/EntityRelation.java deleted file mode 100755 index 5713a858..00000000 --- a/source/mir/entity/EntityRelation.java +++ /dev/null @@ -1,124 +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.entity; - -import mir.storage.StorageObject; -import mir.storage.StorageObjectExc; -import mir.storage.StorageObjectFailure; - -public class EntityRelation { - - public String fromId; - public String toId; - public StorageObject storage; - public int type; - - public final static int TO_ONE = 1; - public final static int TO_MANY = 2; - - - /** - * Kontruktor fuer EntityRelation - * @param fromId ist der Feldname in der ausgehenden Tabelle fuer die Relation - * @param toId ist der Feldname in der Zieltablle - * @param storage ist das StorageObject, ueber das der Zugriff auf die abhaengige - * Tabelle erfolgt. - * @param type ist der Typ der EntityRelation (TO_ONE oder TO_MANY) - */ - - public EntityRelation(String fromId, String toId, StorageObject storage, int type) { - this.fromId = fromId; - this.toId = toId; - this.storage = storage; - this.type = type; - } - - /** - * @return Liefert eine abhaengige Entity mit den verknuepften - * Entities, wenn es sich um eine TO_ONE Beziehung handelt, ansonsten - * null. - */ - - public Entity getOne(Entity entity) throws StorageObjectExc { - if (type==TO_ONE) { - return storage.selectById(entity.getValue(fromId)); - } - else return null; - } - - /** - * @return Liefert eine freemarker.template.SimpleList mit den verknuepften - * Entities, wenn es sich um eine TO_MANY Liste handelt, ansonsten - * null. - */ - - public EntityList getMany(Entity entity) throws StorageObjectFailure{ - if (type==TO_MANY) { - return storage.selectByFieldValue(toId, entity.getValue(fromId)); - } - else return null; - } - - /** - * @return Liefert eine freemarker.template.SimpleList mit den verknuepften - * Entities, wenn es sich um eine TO_MANY Liste handelt, ansonsten - * null. - */ - - public EntityList getMany(Entity entity, String order) throws StorageObjectFailure{ - if (type==TO_MANY) { - return storage.selectByWhereClause(toId+"="+entity.getValue(fromId), order,-1); - } - else return null; - } - - /** - * @return Liefert eine freemarker.template.SimpleList mit den verknuepften - * Entities, wenn es sich um eine TO_MANY Liste handelt, ansonsten - * null. - */ - - public EntityList getMany(Entity entity, String order, String whereClause) throws StorageObjectFailure{ - if (type==TO_MANY) { - return storage.selectByWhereClause(toId + "=" + entity.getValue(fromId) + " and " + whereClause, order,-1); - } - else return null; - } - - /** - * @return The reference name of the related table. - */ - - public String getName() { - return "to" + storage.getTableName(); - } - - -} diff --git a/source/mir/entity/adapter/EntityAdapterDefinition.java b/source/mir/entity/adapter/EntityAdapterDefinition.java index bb132a52..68cdf2f4 100755 --- a/source/mir/entity/adapter/EntityAdapterDefinition.java +++ b/source/mir/entity/adapter/EntityAdapterDefinition.java @@ -29,18 +29,19 @@ */ package mir.entity.adapter; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.*; -import java.util.Map; - -import mir.entity.Entity; +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; -import mir.misc.*; public class EntityAdapterDefinition { - Map calculatedFields; + private Map calculatedFields; public EntityAdapterDefinition() { calculatedFields = new HashMap(); diff --git a/source/mir/entity/adapter/EntityListAdapter.java b/source/mir/entity/adapter/EntityListAdapter.java index 5bf6ae46..f7ae65de 100755 --- a/source/mir/entity/adapter/EntityListAdapter.java +++ b/source/mir/entity/adapter/EntityListAdapter.java @@ -1,117 +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.EntityBrowser; - -public class EntityListAdapter extends AbstractList { - private int skip; - private int maximumLength; - private EntityBrowser browser; - private boolean exhausted = false; - private boolean skipped = false; - - private List cache; - - protected EntityListAdapter(EntityBrowser aBrowser, int aSkip, int aMaximumLength) { - browser = aBrowser; - skip = aSkip; - maximumLength = aMaximumLength; - cache = new Vector(); - } - - protected EntityListAdapter(EntityBrowser aBrowser, int aMaximumLength) { - this(aBrowser, 0, aMaximumLength); - } - - protected EntityListAdapter(EntityBrowser aBrowser) { - this(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.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); + } } \ No newline at end of file diff --git a/source/mir/generator/FreemarkerGenerator.java b/source/mir/generator/FreemarkerGenerator.java index 52efcb76..8b5ec61d 100755 --- a/source/mir/generator/FreemarkerGenerator.java +++ b/source/mir/generator/FreemarkerGenerator.java @@ -142,7 +142,6 @@ public class FreemarkerGenerator implements Generator { } public void remove(String aKey) { - // ML: kinda tricky... } public boolean isEmpty() { diff --git a/source/mir/media/MirMedia.java b/source/mir/media/MirMedia.java index 298809e8..e706d9aa 100755 --- a/source/mir/media/MirMedia.java +++ b/source/mir/media/MirMedia.java @@ -29,10 +29,10 @@ */ package mir.media; -import java.io.InputStream; - +import java.io.InputStream; +import java.util.List; + import mir.entity.Entity; -import freemarker.template.SimpleList; /** * Interface for Media handling in Mir. All media handlers @@ -79,7 +79,7 @@ import freemarker.template.SimpleList; * ) and just override the things that need to be specific. see MediaHandlerAudio * * @author , the Mir-coders group - * @version $Id: MirMedia.java,v 1.18 2003/04/29 02:36:50 zapata Exp $ + * @version $Id: MirMedia.java,v 1.18.2.1 2003/09/03 17:49:38 zapata Exp $ */ public interface MirMedia{ @@ -144,7 +144,7 @@ public interface MirMedia{ * @see mir.entity.Entity * @see mir.misc.StringUtil */ - public abstract SimpleList getURL (Entity ent, Entity mediaTypeEnt) throws MediaExc, MediaFailure; + public abstract List getURL (Entity ent, Entity mediaTypeEnt) throws MediaExc, MediaFailure; /** * Returns the absolute filesystem path to where the media diff --git a/source/mir/misc/HTMLTemplateProcessor.java b/source/mir/misc/HTMLTemplateProcessor.java deleted file mode 100755 index 57281688..00000000 --- a/source/mir/misc/HTMLTemplateProcessor.java +++ /dev/null @@ -1,399 +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.PrintWriter; -import java.net.URLEncoder; -import java.util.GregorianCalendar; -import java.util.Iterator; -import java.util.Locale; -import java.util.Map; -import java.util.Set; - -import javax.servlet.http.HttpServletResponse; - -import mir.config.MirPropertiesConfiguration; -import mir.config.MirPropertiesConfiguration.PropertiesConfigExc; -import mir.entity.Entity; -import mir.entity.EntityList; -import mir.generator.FreemarkerGenerator; -import mir.log.LoggerWrapper; -import mir.storage.StorageObjectFailure; -import mir.util.GeneratorHTMLFunctions; -import mir.util.GeneratorIntegerFunctions; -import mir.util.ResourceBundleGeneratorFunction; - -import org.apache.struts.util.MessageResources; - -import freemarker.template.FileTemplateCache; -import freemarker.template.SimpleHash; -import freemarker.template.SimpleList; -import freemarker.template.SimpleScalar; -import freemarker.template.Template; -import freemarker.template.TemplateModelRoot; - -/** - * Hilfsklasse zum Mergen von Template und Daten - */ -public final class HTMLTemplateProcessor { - - public static String templateDir; - private static final String[] bundles = { "bundles.adminlocal", "bundles.admin" }; - private static MirPropertiesConfiguration configuration; - private static FileTemplateCache templateCache; - private static String docRoot; - private static String actionRoot; - private static LoggerWrapper logger; - - static { - // ML: configuration is not thread safe: it's risky to use it like this - // actually I don't see why HTMLTemplateProcessor needs to be a - // class with static methods. This causes more problems than it solves. - try { - configuration = MirPropertiesConfiguration.instance(); - } - catch (PropertiesConfigExc e) { - e.printStackTrace(); - } - - logger = new LoggerWrapper("TemplateEngine"); - - templateDir = - configuration.getStringWithHome("Mir.TemplateDir"); - templateCache = new FileTemplateCache(templateDir); - templateCache.setLoadingPolicy(FileTemplateCache.LOAD_ON_DEMAND); - // gone in freemarker 1.7.1: templateCache.startAutoUpdate(); - - - docRoot = configuration.getString("RootUri"); - try { - actionRoot = docRoot +configuration.getString("Producer.ActionServlet"); - } - catch (ConfigException ce) { - // if Producer.ActionServlet is not set in the conf file - actionRoot = docRoot + "/Mir"; - } - } - - /** - * empty private constructor, to avoid instantiation - */ - private HTMLTemplateProcessor() { - } - - /** - * Wandelt Liste mit Entities entList in freemarker-Struktur um, mischt die Daten mit - * Template templateFilename und gibt das Ergebnis an den PrintWriter - * out - * - * @param templateFilename - * @param entList - * @param out - * @exception HTMLParseException - */ - - public static void process(HttpServletResponse res, String templateFilename, EntityList entList, PrintWriter out, Locale locale, Locale aFallbackLocale) throws HTMLParseException { - process(res, templateFilename, entList, (String)null, (TemplateModelRoot) null, out, locale, aFallbackLocale); - } - - /** - * Wandelt Entitylist in freemarker-Struktur um, f?gt additionalModel - * unter dem Namen additionalModelName ein und mischt die Daten mit - * Template templateFilename und gibt das Ergebnis an den PrintWriter - * out - * - * @param templateFilename - * @param entList - * @param additionalModelName - * @param additionalModel - * @param out - * @exception HTMLParseException - */ - - public static void process(HttpServletResponse res, String templateFilename, - EntityList entList, String additionalModelName, - TemplateModelRoot additionalModel, PrintWriter out, - Locale locale, Locale aFallbackLocale) throws HTMLParseException { - - SimpleHash modelRoot = new SimpleHash(); - - if (entList == null) { - process(null, templateFilename, modelRoot, null, out, locale, aFallbackLocale); - } - else { - try { - modelRoot = makeSimpleHashWithEntitylistInfos(entList); - - // Quickhack um mal ein Popup mit reinzunhemen .. - if (additionalModelName != null && additionalModel != null) - modelRoot.put(additionalModelName, additionalModel); - - process(res, templateFilename, modelRoot, null, out, locale, aFallbackLocale); - } - catch (StorageObjectFailure e) { - throw new HTMLParseException(e.toString()); - } - } - } - - - /** - * Mischt die freemarker-Struktur tmr mit - * Template templateFilename und gibt das Ergebnis an den PrintWriter - * out - * - * @param templateFilename - * @param mergeData - * @param out - * @exception HTMLParseException - */ - public static void process(HttpServletResponse res, String templateFilename, - TemplateModelRoot tmr, PrintWriter out, - Locale locale, Locale aFallbackLocale) throws HTMLParseException { - process(res, templateFilename, tmr, null, out, locale, aFallbackLocale); - } - - /** - * Mischt die freemarker-Struktur tmr mit - * Template templateFilename und gibt das Ergebnis an den PrintWriter - * out - * - * @param templateFilename - * @param mergeData - * @param out - * @exception HTMLParseException - */ - public static void process(HttpServletResponse res, String templateFilename, - TemplateModelRoot tmr, TemplateModelRoot extra, - PrintWriter out, Locale locale, Locale aFallbackLocale) throws HTMLParseException { - - if (out == null) - throw new HTMLParseException("no outputstream"); - Template tmpl = getTemplateFor(templateFilename); - if (tmpl == null) - throw new HTMLParseException("no template: " + templateFilename); - if (tmr == null) - tmr = new SimpleHash(); - - /** @todo what is this for? (rk) */ - SimpleHash configHash = new SimpleHash(); - - // pass the whole config hash to the templates - Iterator it = configuration.getKeys(); - String key; - while (it.hasNext()) { - key = (String) it.next(); - configHash.put(key, new SimpleScalar( - configuration.getString(key)) - ); - } - - // this does not come directly from the config file - configHash.put("docRoot", new SimpleScalar(docRoot)); - - configHash.put("actionRoot", new SimpleScalar(res.encodeURL(actionRoot))); - configHash.put("now", - new SimpleScalar(StringUtil.date2readableDateTime(new GregorianCalendar()))); - - // this conform to updated freemarker syntax - configHash.put("compressWhitespace", - new freemarker.template.utility.CompressWhitespace()); - - SimpleHash utilityHash = new SimpleHash(); - try { - utilityHash.put("compressWhitespace", - new freemarker.template.utility.CompressWhitespace()); - utilityHash.put("encodeURI", - FreemarkerGenerator.makeAdapter(new GeneratorHTMLFunctions. - encodeURIGeneratorFunction())); - utilityHash.put("encodeHTML", - FreemarkerGenerator.makeAdapter(new GeneratorHTMLFunctions. - encodeHTMLGeneratorFunction())); - utilityHash.put("isOdd", - FreemarkerGenerator.makeAdapter(new GeneratorIntegerFunctions. - isOddFunction())); - utilityHash.put("increment", - FreemarkerGenerator.makeAdapter(new GeneratorIntegerFunctions. - incrementFunction())); - } - catch (Throwable t) { - throw new HTMLParseException(t.getMessage()); - } - - SimpleHash outPutHash = new SimpleHash(); - - if (extra != null) { - outPutHash.put("extra", extra); - } - outPutHash.put("data", tmr); - outPutHash.put("config", configHash); - outPutHash.put("utility", utilityHash); - - MessageResources messages[] = new MessageResources[bundles.length]; - - for (int i=0; iTitle: EntityBatchingProducerNode

+ *

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

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ + public class EntityBatchingProducerNode implements ProducerNode { private String batchInfoKey; private String batchDataKey; @@ -110,10 +125,6 @@ public class EntityBatchingProducerNode implements ProducerNode { int nrEntitiesPerBatch; int minNrEntitiesInFirstBatch; -// ML: The order by clause should lead to a result set in _reverse order_: the first row will be -// the last entity presented on the last page - - try { nrBatchesToProcess = ParameterExpander.evaluateIntegerExpressionWithDefault( aValueMap, nrBatchesToProcessExpression, -1 ); diff --git a/source/mir/producer/reader/DefaultProducerNodeBuilders.java b/source/mir/producer/reader/DefaultProducerNodeBuilders.java index 63fbf7d4..90bef9d5 100755 --- a/source/mir/producer/reader/DefaultProducerNodeBuilders.java +++ b/source/mir/producer/reader/DefaultProducerNodeBuilders.java @@ -818,8 +818,6 @@ public class DefaultProducerNodeBuilders { private final static String[] BATCHER_OPTIONAL_ATTRIBUTES = { BATCHER_SELECTION_ATTRIBUTE, BATCHER_ORDER_ATTRIBUTE, BATCHER_MINBATCHSIZE_ATTRIBUTE, BATCHER_SKIP_ATTRIBUTE, BATCHER_PROCESS_ATTRIBUTE }; private final static String[] BATCHER_SUBNODES = { BATCHER_BATCH_SUBNODE, BATCHER_BATCHLIST_SUBNODE }; - // ML: batchSize, minBatchSize, skip should be expressions! - private EntityAdapterModel model; private String batchDataKey; private String batchInfoKey; diff --git a/source/mir/rss/RDFResource.java b/source/mir/rss/RDFResource.java index c720a558..b0c68a94 100755 --- a/source/mir/rss/RDFResource.java +++ b/source/mir/rss/RDFResource.java @@ -29,7 +29,8 @@ */ package mir.rss; -import java.util.*; +import java.util.HashMap; +import java.util.Map; public class RDFResource { private String identifier; diff --git a/source/mir/servlet/AbstractServlet.java b/source/mir/servlet/AbstractServlet.java index e343842e..441ee335 100755 --- a/source/mir/servlet/AbstractServlet.java +++ b/source/mir/servlet/AbstractServlet.java @@ -1,271 +1,278 @@ -/* - * 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.servlet; - -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Locale; -import java.sql.*; - -import javax.servlet.ServletConfig; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - - -import com.codestudio.util.*; -import com.codestudio.util.JDBCPoolMetaData; -import com.codestudio.util.SQLManager; - -import mir.config.MirPropertiesConfiguration; -import mir.config.MirPropertiesConfiguration.PropertiesConfigExc; -import mir.log.LoggerWrapper; -import mircoders.global.*; - -/** - * Title: Mir - * Description: Abstract servlet-class - * Copyright: Copyright (c) 2001, 2002 - * Company: Mir-coders group - * @author idfx, the Mir-coders group - * @version $Id: AbstractServlet.java,v 1.30.2.3 2003/06/28 04:04:25 zapata Exp $ - */ - -public abstract class AbstractServlet extends HttpServlet { - protected static String lang; - protected LoggerWrapper logger; - protected MirPropertiesConfiguration configuration; - - /** - * Constructor for AbstractServlet. - */ - public AbstractServlet() { - super(); - } - - protected void setNoCaching(HttpServletResponse aResponse) { - //nothing in Mir can or should be cached as it's all dynamic... - // - //this needs to be done here and not per page (via meta tags) as some - //browsers have problems w/ it per-page -mh - aResponse.setHeader("Pragma", "no-cache"); - aResponse.setDateHeader("Expires", 0); - aResponse.setHeader("Cache-Control", "no-cache"); - } - - /** - * Bind the language to the session - */ - protected void setLanguage(HttpSession session, String language) { - logger.debug("setting language to " + language); - - session.setAttribute("language", language); - session.setAttribute("locale", new Locale(language, "")); - } - - /** - * Get the session-bound language - */ - protected String getLanguage(HttpServletRequest aRequest, HttpSession session) { - String lang = (String) session.getAttribute("language"); - - if (lang == null || lang.length()==0) { - lang = getAcceptLanguage(aRequest); - } - - return lang; - } - - /** - * get the locale either from the session or the accept-language header ot the request - * this supersedes getLanguage for the new i18n - */ - public Locale getLocale(HttpServletRequest aRequest) { - Locale loc = null; - HttpSession session = aRequest.getSession(false); - if (session != null) { - // session can be null in case of logout - loc = (Locale) session.getAttribute("locale"); - } - // if there is nothing in the session get it fron the accept-language - if (loc == null) { - loc = aRequest.getLocale(); - } - - logger.debug("getting locale: " + loc.getLanguage()); - - return loc; - } - - /** - * Checks the Accept-Language of the client browser. - * If this language is available it returns its country-code, - * else it returns the standard-language - */ - protected String getAcceptLanguage(HttpServletRequest aRequest) { - Locale loc = aRequest.getLocale(); - lang = loc.getLanguage(); - return lang; - } - - /** - * @see javax.servlet.Servlet#init(javax.servlet.ServletConfig) - */ - public void init(ServletConfig config) throws ServletException { - super.init(config); - - MirPropertiesConfiguration.setContext(config.getServletContext()); - try { - configuration = MirPropertiesConfiguration.instance(); - } - catch (Throwable t) { - throw new ServletException("can't read configuration: " + t.toString()); - } - - logger = new LoggerWrapper("Servlet"); - - try { - MirGlobal.localizer(); - } - catch (Throwable t) { - logger.fatal("can't get localizer: " + t.toString()); - throw new ServletException("can't get localizer: " + t.toString()); - } - - String dbUser = configuration.getString("Database.Username"); - String dbPassword = configuration.getString("Database.Password"); - String dbHost = configuration.getString("Database.Host"); - String dbPort = configuration.getString("Database.Port"); - String dbAdapName = configuration.getString("Database.Adaptor"); - String dbName = configuration.getString("Database.Name"); - String dbDriver = configuration.getString("Database.Driver"); - String dbUrl = "jdbc:postgresql://"+dbHost+":"+dbPort+"/"+dbName; - int dbMin = configuration.getInteger("Database.poolMin", 1); - int dbMax = configuration.getInteger("Database.poolMax", 10); - - JDBCPoolMetaData meta = new JDBCPoolMetaData(); - meta.setDbname(dbName); - meta.setDriver(dbDriver); - meta.setURL(dbUrl); - meta.setUserName(dbUser); - meta.setPassword(dbPassword); - meta.setJNDIName("mir"); - meta.setMaximumSize(dbMax); - meta.setMinimumSize(dbMin); - meta.setPoolPreparedStatements(false); - meta.setCacheEnabled(false); - meta.setCacheSize(15); - meta.setDebugging(false); - - SQLManager manager = SQLManager.getInstance(); - - JDBCPool pool = null; - if (manager != null) { - pool = manager.createPool(meta); - } - - Connection connection; - try { - connection = pool.requestConnection(); - pool.closeConnection(connection); - } - catch (Throwable t) { - logger.fatal("Can't connect to database: " + t.toString()); - throw new ServletException("Can't connect to database: " + t.toString()); - } - } - - private void setEncoding(HttpServletRequest request){ - try { - Class reqClass = request.getClass(); - Method method = reqClass.getMethod("setCharacterEncoding", new Class[]{String.class}); - String encoding = configuration.getString("Mir.DefaultHTMLCharset"); - method.invoke(request, new Object[]{encoding}); - } catch (NoSuchMethodException e) { - // TODO set the encoding in a zapata-way -// logger.warn("set encoding not yet implemented: " + e.getMessage()); - } catch (SecurityException e) { - logger.error(e.getMessage()); - e.printStackTrace(); - } catch (IllegalArgumentException e) { - logger.error(e.getMessage()); - e.printStackTrace(); - } catch (IllegalAccessException e) { - logger.error(e.getMessage()); - e.printStackTrace(); - } catch (InvocationTargetException e) { - logger.error(e.getMessage()); - e.printStackTrace(); - } - } - - protected final void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - doPost(request, response); - } - - protected final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - if ((configuration.getString("RootUri") == null) || configuration.getString("RootUri").equals("")) { - configuration.setProperty("RootUri", request.getContextPath()); - } - setEncoding(request); - process(request, response); - } - - abstract public void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException; - - /** - * Selects the language for the response. - * - * @param session - * @param aRequest - */ - protected void checkLanguage(HttpSession aSession, HttpServletRequest aRequest) { - String requestLanguage = aRequest.getParameter("language"); - String sessionLanguage = (String) aSession.getAttribute("language"); - String acceptLanguage = aRequest.getLocale().getLanguage(); - String defaultLanguage = configuration.getString("Mir.Login.DefaultLanguage", "en"); - - String language = requestLanguage; - - if (language==null) - language = sessionLanguage; - - if (language==null) - language = acceptLanguage; - - if (language==null) - language = defaultLanguage; - - setLanguage(aSession, language); - } -} +/* + * 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.servlet; + +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.sql.Connection; +import java.util.Locale; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import com.codestudio.util.JDBCPool; +import com.codestudio.util.JDBCPoolMetaData; +import com.codestudio.util.SQLManager; + +import mir.config.MirPropertiesConfiguration; +import mir.log.LoggerWrapper; + +import mircoders.global.MirGlobal; + +/** + * Title: Mir + * Description: Abstract servlet-class + * Copyright: Copyright (c) 2001, 2002 + * Company: Mir-coders group + * @author idfx, the Mir-coders group + * @version $Id: AbstractServlet.java,v 1.30.2.4 2003/09/03 17:49:38 zapata Exp $ + */ + +public abstract class AbstractServlet extends HttpServlet { + protected static String lang; + protected LoggerWrapper logger; + protected MirPropertiesConfiguration configuration; + + /** + * Constructor for AbstractServlet. + */ + public AbstractServlet() { + super(); + } + + protected void setNoCaching(HttpServletResponse aResponse) { + //nothing in Mir can or should be cached as it's all dynamic... + // + //this needs to be done here and not per page (via meta tags) as some + //browsers have problems w/ it per-page -mh + aResponse.setHeader("Pragma", "no-cache"); + aResponse.setDateHeader("Expires", 0); + aResponse.setHeader("Cache-Control", "no-cache"); + } + + /** + * Bind the language to the session + */ + protected void setLanguage(HttpSession session, String language) { + logger.debug("setting language to " + language); + + session.setAttribute("language", language); + session.setAttribute("locale", new Locale(language, "")); + } + + /** + * Get the session-bound language + */ + protected String getLanguage(HttpServletRequest aRequest, HttpSession session) { + String lang = (String) session.getAttribute("language"); + + if (lang == null || lang.length()==0) { + lang = getAcceptLanguage(aRequest); + } + + return lang; + } + + /** + * get the locale either from the session or the accept-language header ot the request + * this supersedes getLanguage for the new i18n + */ + public Locale getLocale(HttpServletRequest aRequest) { + Locale loc = null; + HttpSession session = aRequest.getSession(false); + if (session != null) { + // session can be null in case of logout + loc = (Locale) session.getAttribute("locale"); + } + // if there is nothing in the session get it fron the accept-language + if (loc == null) { + loc = aRequest.getLocale(); + } + + logger.debug("getting locale: " + loc.getLanguage()); + + return loc; + } + + /** + * Checks the Accept-Language of the client browser. + * If this language is available it returns its country-code, + * else it returns the standard-language + */ + protected String getAcceptLanguage(HttpServletRequest aRequest) { + Locale loc = aRequest.getLocale(); + lang = loc.getLanguage(); + return lang; + } + + /** + * @see javax.servlet.Servlet#init(javax.servlet.ServletConfig) + */ + public void init(ServletConfig config) throws ServletException { + super.init(config); + + MirPropertiesConfiguration.setContext(config.getServletContext()); + try { + configuration = MirPropertiesConfiguration.instance(); + } + catch (Throwable t) { + throw new ServletException("can't read configuration: " + t.toString()); + } + + logger = new LoggerWrapper("Servlet"); + + try { + MirGlobal.localizer(); + } + catch (Throwable t) { + logger.fatal("can't get localizer: " + t.toString()); + throw new ServletException("can't get localizer: " + t.toString()); + } + + String dbUser = configuration.getString("Database.Username"); + String dbPassword = configuration.getString("Database.Password"); + String dbHost = configuration.getString("Database.Host"); + String dbPort = configuration.getString("Database.Port"); + String dbAdapName = configuration.getString("Database.Adaptor"); + String dbName = configuration.getString("Database.Name"); + String dbDriver = configuration.getString("Database.Driver"); + String dbUrl = "jdbc:postgresql://"+dbHost+":"+dbPort+"/"+dbName; + int dbMin = configuration.getInteger("Database.poolMin", 1); + int dbMax = configuration.getInteger("Database.poolMax", 10); + + JDBCPoolMetaData meta = new JDBCPoolMetaData(); + meta.setDbname(dbName); + meta.setDriver(dbDriver); + meta.setURL(dbUrl); + meta.setUserName(dbUser); + meta.setPassword(dbPassword); + meta.setJNDIName("mir"); + meta.setMaximumSize(dbMax); + meta.setMinimumSize(dbMin); + meta.setPoolPreparedStatements(false); + meta.setCacheEnabled(false); + meta.setCacheSize(15); + meta.setDebugging(false); + + SQLManager manager = SQLManager.getInstance(); + + JDBCPool pool = null; + if (manager != null) { + pool = manager.createPool(meta); + } + + Connection connection; + try { + connection = pool.requestConnection(); + pool.closeConnection(connection); + } + catch (Throwable t) { + logger.fatal("Can't connect to database: " + t.toString()); + throw new ServletException("Can't connect to database: " + t.toString()); + } + } + + private void setEncoding(HttpServletRequest request){ + try { + logger.info("Request has encoding: " + request.getCharacterEncoding()); + logger.info("Config stipulates encoding: " + configuration.getString("Mir.DefaultHTMLCharset")); + Class reqClass = request.getClass(); + Method method = reqClass.getMethod("setCharacterEncoding", new Class[]{String.class}); + String encoding = configuration.getString("Mir.DefaultHTMLCharset"); + method.invoke(request, new Object[]{encoding}); + logger.info("Request now has encoding: " + request.getCharacterEncoding()); + } + catch (NoSuchMethodException e) { + // TODO set the encoding in a zapata-way +// logger.warn("set encoding not yet implemented: " + e.getMessage()); + } + catch (SecurityException e) { + logger.error(e.getMessage()); + e.printStackTrace(); + } + catch (IllegalArgumentException e) { + logger.error(e.getMessage()); + e.printStackTrace(); + } + catch (IllegalAccessException e) { + logger.error(e.getMessage()); + e.printStackTrace(); + } + catch (InvocationTargetException e) { + logger.error(e.getMessage()); + e.printStackTrace(); + } + } + + protected final void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + protected final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + if ((configuration.getString("RootUri") == null) || configuration.getString("RootUri").equals("")) { + configuration.setProperty("RootUri", request.getContextPath()); + } + setEncoding(request); + process(request, response); + } + + abstract public void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException; + + /** + * Selects the language for the response. + * + * @param session + * @param aRequest + */ + protected void checkLanguage(HttpSession aSession, HttpServletRequest aRequest) { + String requestLanguage = aRequest.getParameter("language"); + String sessionLanguage = (String) aSession.getAttribute("language"); + String acceptLanguage = aRequest.getLocale().getLanguage(); + String defaultLanguage = configuration.getString("Mir.Login.DefaultLanguage", "en"); + + String language = requestLanguage; + + if (language==null) + language = sessionLanguage; + + if (language==null) + language = acceptLanguage; + + if (language==null) + language = defaultLanguage; + + setLanguage(aSession, language); + } +} diff --git a/source/mir/servlet/ServletModule.java b/source/mir/servlet/ServletModule.java index c8f252ac..42519db6 100755 --- a/source/mir/servlet/ServletModule.java +++ b/source/mir/servlet/ServletModule.java @@ -29,58 +29,57 @@ */ package mir.servlet; -import java.io.PrintWriter; import java.util.HashMap; +import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import mir.config.MirPropertiesConfiguration; import mir.config.MirPropertiesConfiguration.PropertiesConfigExc; -import mir.entity.EntityList; +import mir.entity.adapter.EntityAdapterDefinition; +import mir.entity.adapter.EntityAdapterEngine; +import mir.entity.adapter.EntityAdapterModel; import mir.log.LoggerWrapper; -import mir.misc.HTMLTemplateProcessor; -import mir.misc.LineFilterWriter; import mir.module.AbstractModule; import mir.storage.StorageObject; import mir.util.HTTPRequestParser; -import mircoders.servlet.*; -import freemarker.template.SimpleHash; -import freemarker.template.TemplateModelRoot; - - - +import mir.util.URLBuilder; +import mircoders.servlet.ServletHelper; /** - * Abstract class ServletModule provides the base functionality for servlets. - * Deriving a class from ServletModule enables class to insert/edit/update/delete - * and list Entity from a Database via mainModule. - * - * - * Abstrakte Klasse ServletModule stellt die Basisfunktionalitaet der - * abgeleiteten ServletModule zur Verf?gung. * - * @version 28.6.1999 - * @author RK + *

Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 */ public abstract class ServletModule { - public String defaultAction; protected LoggerWrapper logger; protected MirPropertiesConfiguration configuration; - protected AbstractModule mainModule; protected Locale fallbackLocale; - protected String templateListString; - protected String templateObjektString; - protected String templateConfirmString; + + protected AbstractModule mainModule; + protected String definition; + protected EntityAdapterModel model; + + protected String listGenerator; + protected String editGenerator; + protected String deleteConfirmationGenerator; + protected int nrEntitiesPerListPage; public ServletModule(){ + definition = null; + model = null; + try { configuration = MirPropertiesConfiguration.instance(); } @@ -88,20 +87,30 @@ public abstract class ServletModule { throw new RuntimeException("Can't get configuration: " + e.getMessage()); } + listGenerator = configuration.getString("ServletModule."+getOperationModuleName()+".ListTemplate"); + editGenerator = configuration.getString("ServletModule."+getOperationModuleName()+".EditTemplate"); + deleteConfirmationGenerator = configuration.getString("ServletModule."+getOperationModuleName()+".DeleteConfirmationTemplate"); + nrEntitiesPerListPage = + configuration.getInt("ServletModule."+getOperationModuleName()+".ListSize", + configuration.getInt("ServletModule.Default.ListSize", 20)); + fallbackLocale = new Locale(configuration.getString("Mir.Admin.FallbackLanguage", "en"), ""); } /** - * Singelton - Methode muss in den abgeleiteten Klassen ueberschrieben werden. - * @return ServletModule + * Singleton instance retrievel method. MUST be overridden in subclasses. + * + * @return ServletModule the single instance of the servletmodule class */ public static ServletModule getInstance() { return null; } /** - * get the module name to be used for generic operations like delete. + * Get the module name + * + * @return */ protected String getOperationModuleName() { return getClass().getName().substring((new String("mircoders.servlet.ServletModule")).length()); @@ -111,16 +120,16 @@ public abstract class ServletModule { * get the locale either from the session or the accept-language header ot the request * this supersedes getLanguage for the new i18n */ - public Locale getLocale(HttpServletRequest req) { + public Locale getLocale(HttpServletRequest aRequest) { Locale loc = null; - HttpSession session = req.getSession(false); + HttpSession session = aRequest.getSession(false); if (session != null) { // session can be null in case of logout loc = (Locale) session.getAttribute("locale"); } // if there is nothing in the session get it fron the accept-language if (loc == null) { - loc = req.getLocale(); + loc = aRequest.getLocale(); } return loc; } @@ -129,216 +138,212 @@ public abstract class ServletModule { * get the locale either from the session or the accept-language header ot the request * this supersedes getLanguage for the new i18n */ - public Locale getFallbackLocale(HttpServletRequest req) { + public Locale getFallbackLocale(HttpServletRequest aRequest) { return fallbackLocale; } - public void redirect(HttpServletResponse aResponse, String aQuery) throws ServletModuleExc, ServletModuleFailure { - try { - aResponse.sendRedirect(aResponse.encodeRedirectURL(MirPropertiesConfiguration.instance().getString("RootUri") + "/Mir?"+aQuery)); - } - catch (Throwable t) { - throw new ServletModuleFailure("ServletModule.redirect: " +t.getMessage(), t); - } - } - /** - * list(req,res) - generische Listmethode. Wennn die Funktionalitaet - * nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse - * ueberschreiben werden. + * Function to specify the default ordering for lists. May be overridden. * - * @param req Http-Request, das vom Dispatcher durchgereicht wird - * @param res Http-Response, die vom Dispatcher durchgereicht wird + * + * @return */ - public void list(HttpServletRequest req, HttpServletResponse res) - throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { - try { - EntityList theList; - String offsetParam = req.getParameter("offset"); - int offset = 0; - PrintWriter out = res.getWriter(); - - // hier offsetcode bearbeiten - if (offsetParam != null && !offsetParam.equals("")) { - offset = Integer.parseInt(offsetParam); - } - if (req.getParameter("next") != null) { - offset = Integer.parseInt(req.getParameter("nextoffset")); - } - else { - if (req.getParameter("prev") != null) { - offset = Integer.parseInt(req.getParameter("prevoffset")); - } - } - theList = mainModule.getByWhereClause(null, offset); + public String getDefaultListOrdering() { - HTMLTemplateProcessor.process(res, templateListString, theList, null, null, out, getLocale(req), getFallbackLocale(req)); + if (mainModule!=null && mainModule.getStorageObject()!=null){ + if (mainModule.getStorageObject().getFields().contains("webdb_create")) + return "webdb_create desc"; } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - /** - * add(req,res) - generische Addmethode. Wennn die Funktionalitaet - * nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse - * ueberschreiben werden. - * @param req Http-Request, das vom Dispatcher durchgereicht wird - * @param res Http-Response, die vom Dispatcher durchgereicht wird - */ - public void add(HttpServletRequest req, HttpServletResponse res) - throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { - - try { - SimpleHash mergeData = new SimpleHash(); - mergeData.put("new", "1"); - deliver(req, res, mergeData, templateObjektString); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } + return "id asc"; } /** - * insert(req,res) - generische Insertmethode, folgt auf add. - * Wennn die Funktionalitaet - * nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse - * ueberschreiben werden. * - * @param req Http-Request, das vom Dispatcher durchgereicht wird - * @param res Http-Response, die vom Dispatcher durchgereicht wird + * @param aResponse + * @param aQuery + * @throws ServletModuleExc + * @throws ServletModuleFailure */ - public void insert(HttpServletRequest req, HttpServletResponse res) - throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { + public void redirect(HttpServletResponse aResponse, String aQuery) throws ServletModuleExc, ServletModuleFailure { try { - Map withValues = getIntersectingValues(req, mainModule.getStorageObject()); - logger.debug("--trying to add..."); - String id = mainModule.add(withValues); - logger.debug("--trying to deliver..." + id); - list(req, res); + aResponse.sendRedirect(aResponse.encodeRedirectURL(MirPropertiesConfiguration.instance().getString("RootUri") + "/Mir?"+aQuery)); } - catch (Throwable e) { - throw new ServletModuleFailure(e); + catch (Throwable t) { + throw new ServletModuleFailure("ServletModule.redirect: " +t.getMessage(), t); } } /** - * delete(req,res) - generic delete method. Can be overridden in subclasses. + * Generic list method * + * @param aRequest + * @param aResponse + * @throws ServletModuleExc + * @throws ServletModuleUserExc + * @throws ServletModuleFailure */ -/* - public void delete(HttpServletRequest req, HttpServletResponse res) - throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { + + public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc + { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + + String where = requestParser.getParameter("where"); + String order = requestParser.getParameterWithDefault("order", getDefaultListOrdering()); + int offset = requestParser.getIntegerWithDefault("offset", 0); + + returnList(aRequest, aResponse, where, order, offset); + } + + + public void returnList(HttpServletRequest aRequest, HttpServletResponse aResponse, + String aWhereClause, String anOrderByClause, int anOffset) throws ServletModuleExc { + + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + URLBuilder urlBuilder = new URLBuilder(); + int count; + try { - String idParam = req.getParameter("id"); + Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}); - if (idParam == null) - throw new ServletModuleExc("Invalid call to delete: no id supplied"); + List list = + EntityAdapterEngine.retrieveAdapterList(model, definition, aWhereClause, anOrderByClause, nrEntitiesPerListPage, anOffset); + + responseData.put("nexturl", null); + responseData.put("prevurl", null); + responseData.put("module", getOperationModuleName()); - String confirmParam = req.getParameter("confirm"); - String cancelParam = req.getParameter("cancel"); - if (confirmParam == null && cancelParam == null) { - SimpleHash mergeData = new SimpleHash(); - - mergeData.put("module", getOperationModuleName()); - mergeData.put("infoString", getOperationModuleName() + ": " + idParam); - mergeData.put("id", idParam); - mergeData.put("where", req.getParameter("where")); - mergeData.put("order", req.getParameter("order")); - mergeData.put("offset", req.getParameter("offset")); - // this stuff is to be compatible with the other more advanced - // search method used for media and comments - mergeData.put("query_media_folder", req.getParameter("query_media_folder")); - mergeData.put("query_is_published", req.getParameter("query_is_published")); - mergeData.put("query_text", req.getParameter("query_text")); - mergeData.put("query_field", req.getParameter("query_field")); - - deliver(req, res, mergeData, templateConfirmString); + count=mainModule.getSize(aWhereClause); + + urlBuilder.setValue("module", getOperationModuleName()); + urlBuilder.setValue("do", "list"); + urlBuilder.setValue("where", aWhereClause); + urlBuilder.setValue("order", anOrderByClause); + + urlBuilder.setValue("searchfield", requestParser.getParameter("searchfield")); + urlBuilder.setValue("searchtext", requestParser.getParameter("searchtext")); + urlBuilder.setValue("searchispublished", requestParser.getParameter("searchispublished")); + urlBuilder.setValue("searchstatus", requestParser.getParameter("searchstatus")); + urlBuilder.setValue("searchorder", requestParser.getParameter("searchorder")); + + responseData.put("searchfield", requestParser.getParameter("searchfield")); + responseData.put("searchtext", requestParser.getParameter("searchtext")); + responseData.put("searchispublished", requestParser.getParameter("searchispublished")); + responseData.put("searchstatus", requestParser.getParameter("searchstatus")); + responseData.put("searchorder", requestParser.getParameter("searchorder")); + + urlBuilder.setValue("offset", anOffset); + responseData.put("offset" , new Integer(anOffset).toString()); + responseData.put("thisurl" , urlBuilder.getQuery()); + + if (count>anOffset+nrEntitiesPerListPage) { + urlBuilder.setValue("offset", anOffset + nrEntitiesPerListPage); + responseData.put("nexturl" , urlBuilder.getQuery()); } - else { - if (confirmParam != null && !confirmParam.equals("")) { - //theLog.printInfo("delete confirmed!"); - mainModule.deleteById(idParam); - list(req, res); // back to list - } - else { - if (req.getParameter("where") != null) - list(req, res); - else - edit(req, res); - } + + if (anOffset>0) { + urlBuilder.setValue("offset", Math.max(anOffset - nrEntitiesPerListPage, 0)); + responseData.put("prevurl" , urlBuilder.getQuery()); } + + responseData.put("entities", list); + responseData.put("from" , Integer.toString(anOffset+1)); + responseData.put("count", Integer.toString(count)); + responseData.put("to", Integer.toString(Math.min(anOffset+nrEntitiesPerListPage, count))); + + ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator); } catch (Throwable e) { throw new ServletModuleFailure(e); } } -*/ - public void confirmdelete(HttpServletRequest aRequest, HttpServletResponse aResponse) { + + public void editObject(HttpServletRequest aRequest, HttpServletResponse aResponse, Object anObject, boolean anIsNew, String anId) throws ServletModuleExc { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + URLBuilder urlBuilder = new URLBuilder(); + EntityAdapterModel model; + try { - String idParam = aRequest.getParameter("id"); - String confirmParam = aRequest.getParameter("confirm"); - String cancelParam = aRequest.getParameter("cancel"); + Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}); - if (confirmParam != null && !confirmParam.equals("")) { - mainModule.deleteById(idParam); - redirect(aResponse, aRequest.getParameter("okurl")); + responseData.put("module", getOperationModuleName()); + responseData.put("entity", anObject); + responseData.put("new", new Boolean(anIsNew)); + + + urlBuilder.setValue("module", getOperationModuleName()); + urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl")); + if (anIsNew) + urlBuilder.setValue("do", "add"); + else { + urlBuilder.setValue("id", anId); + urlBuilder.setValue("do", "edit"); } - else - redirect(aResponse, aRequest.getParameter("cancelurl")); + responseData.put("returnurl", requestParser.getParameter("returnurl")); + responseData.put("thisurl", urlBuilder.getQuery()); + + ServletHelper.generateResponse(aResponse.getWriter(), responseData, editGenerator); } - catch (Throwable t) { - throw new ServletModuleFailure(t); + catch (Throwable e) { + throw new ServletModuleFailure(e); } } - public void delete(HttpServletRequest aRequest, HttpServletResponse aResponse) + + /** + * Generic add method + * + * @param aRequest + * @param aResponse + * @throws ServletModuleExc + * @throws ServletModuleUserExc + * @throws ServletModuleFailure + */ + public void add(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { - try { - String idParam = aRequest.getParameter("id"); - if (idParam == null) - throw new ServletModuleExc("Invalid call to delete: no id supplied"); + Map object = new HashMap(); - Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}); + Iterator i = mainModule.getStorageObject().getFields().iterator(); - responseData.put("module", getOperationModuleName()); - responseData.put("id", idParam); - responseData.put("cancelurl", aRequest.getParameter("cancelurl")); - responseData.put("okurl", aRequest.getParameter("okurl")); + while (i.hasNext()) + object.put(i.next(), ""); - ServletHelper.generateResponse(aResponse.getWriter(), responseData, templateConfirmString); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } + initializeNewObject(object, aRequest, aResponse); + + editObject(aRequest, aResponse, object, true, null); + } + + protected void initializeNewObject(Map aNewObject, HttpServletRequest aRequest, HttpServletResponse aResponse) { } /** * Method called when the user edits an object. * - * @param req - * @param res + * @param aRequest + * @param aResponse * @throws ServletModuleExc * @throws ServletModuleUserExc * @throws ServletModuleFailure */ - public void edit(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { - edit(req, res, req.getParameter("id")); + public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { + edit(aRequest, aResponse, aRequest.getParameter("id")); } /** - * edit(req,res) - generische Editmethode. Wennn die Funktionalitaet - * nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse - * ueberschreiben werden. + * Generic edit method * - * @param req Http-Request, das vom Dispatcher durchgereicht wird - * @param res Http-Response, die vom Dispatcher durchgereicht wird + * @param aRequest + * @param aResponse + * @param anIdentifier + * @throws ServletModuleExc + * @throws ServletModuleUserExc + * @throws ServletModuleFailure */ public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse, String anIdentifier) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { try { - deliver(aRequest, aResponse, mainModule.getById(anIdentifier), templateObjektString); + editObject(aRequest, aResponse, model.makeEntityAdapter(definition, mainModule.getById(anIdentifier)), false, anIdentifier); } catch (Throwable e) { throw new ServletModuleFailure(e); @@ -346,29 +351,30 @@ public abstract class ServletModule { } /** - * update(req,res) - generische Updatemethode. Wennn die Funktionalitaet - * nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse - * ueberschreiben werden. + * Generic update method * - * @param req Http-Request, das vom Dispatcher durchgereicht wird - * @param res Http-Response, die vom Dispatcher durchgereicht wird + * @param aRequest + * @param aResponse + * @throws ServletModuleExc + * @throws ServletModuleUserExc + * @throws ServletModuleFailure */ - - public void update(HttpServletRequest req, HttpServletResponse res) + public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { try { - String idParam = req.getParameter("id"); - Map withValues = getIntersectingValues(req, mainModule.getStorageObject()); + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + + String id = aRequest.getParameter("id"); + Map withValues = getIntersectingValues(aRequest, mainModule.getStorageObject()); + mainModule.set(withValues); - String id = mainModule.set(withValues); - String whereParam = req.getParameter("where"); - String orderParam = req.getParameter("order"); + String returnUrl = requestParser.getParameter("returnurl"); - if ((whereParam != null && !whereParam.equals("")) || (orderParam != null && !orderParam.equals(""))) { - list(req, res); + if (returnUrl!=null) { + redirect(aResponse, returnUrl); } else { - edit(req, res); + edit(aRequest, aResponse, id); } } catch (Throwable e) { @@ -377,95 +383,93 @@ public abstract class ServletModule { } /** - * deliver liefert das Template mit dem Filenamen templateFilename - * an den HttpServletResponse res aus, nachdem es mit den Daten aus - * TemplateModelRoot rtm gemischt wurde + * Generic insert method * - * @param res Http-Response, die vom Dispatcher durchgereicht wird - * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den - * Daten, die ins Template gemerged werden sollen. - * @param tmpl Name des Templates - * @exception ServletModuleException + * @param aRequest + * @param aResponse + * @throws ServletModuleExc + * @throws ServletModuleUserExc + * @throws ServletModuleFailure */ - public void deliver(HttpServletRequest req, HttpServletResponse res, TemplateModelRoot rtm, - TemplateModelRoot popups, String templateFilename) throws ServletModuleFailure { - if (rtm == null) - rtm = new SimpleHash(); - + public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse) + throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { try { - PrintWriter out = res.getWriter(); - HTMLTemplateProcessor.process(res, templateFilename, rtm, popups, out, getLocale(req), getFallbackLocale(req)); - - // we default to admin bundles here, which is not exactly beautiful... - // but this whole producer stuff is going to be rewritten soon. - // ServletModuleOpenIndy overwrites deliver() to use open bundles - // (br1) - out.close(); + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + + Map object = getIntersectingValues(aRequest, mainModule.getStorageObject()); + + String id = processInstertedObject(object, aRequest, aResponse); + + String returnUrl = requestParser.getParameter("returnurl"); + + if (returnUrl!=null) { + redirect(aResponse, returnUrl); + } + else { + edit(aRequest, aResponse, id); + } } catch (Throwable e) { throw new ServletModuleFailure(e); } } + public String processInstertedObject(Map anObject, HttpServletRequest aRequest, HttpServletResponse aResponse) { + try { + return mainModule.add(anObject); + } + catch (Throwable t) { + throw new ServletModuleFailure(t); + } + }; /** - * deliver liefert das Template mit dem Filenamen templateFilename - * an den HttpServletResponse res aus, nachdem es mit den Daten aus - * TemplateModelRoot rtm gemischt wurde - * - * @param res Http-Response, die vom Dispatcher durchgereicht wird - * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den - * Daten, die ins Template gemerged werden sollen. - * @param tmpl Name des Templates - * @exception ServletModuleException - */ - public void deliver(HttpServletRequest req, HttpServletResponse res, - TemplateModelRoot rtm, String templateFilename) throws ServletModuleFailure { - deliver(req, res, rtm, null, templateFilename); - } - - /** - * deliver liefert das Template mit dem Filenamen templateFilename - * an den HttpServletResponse res aus, nachdem es mit den Daten aus - * TemplateModelRoot rtm gemischt wurde * - * @param res Http-Response, die vom Dispatcher durchgereicht wird - * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den - * Daten, die ins Template gemerged werden sollen. - * @param tmpl Name des Templates - * @exception ServletModuleException + * @param aRequest + * @param aResponse */ - public void deliver_compressed(HttpServletRequest req, HttpServletResponse res, - TemplateModelRoot rtm, String templateFilename) - throws ServletModuleFailure { - if (rtm == null) rtm = new SimpleHash(); + public void confirmdelete(HttpServletRequest aRequest, HttpServletResponse aResponse) { try { - PrintWriter out = new LineFilterWriter(res.getWriter()); - //PrintWriter out = res.getWriter(); - HTMLTemplateProcessor.process(res, templateFilename, rtm, null, out, getLocale(req), getFallbackLocale(req)); - out.close(); + String idParam = aRequest.getParameter("id"); + String confirmParam = aRequest.getParameter("confirm"); + String cancelParam = aRequest.getParameter("cancel"); + + if (confirmParam != null && !confirmParam.equals("")) { + mainModule.deleteById(idParam); + redirect(aResponse, aRequest.getParameter("okurl")); + } + else + redirect(aResponse, aRequest.getParameter("cancelurl")); } - catch (Throwable e) { - throw new ServletModuleFailure(e); + catch (Throwable t) { + throw new ServletModuleFailure(t); } } /** - * deliver liefert das Template mit dem Filenamen templateFilename - * an den HttpServletResponse res aus, nachdem es mit den Daten aus - * TemplateModelRoot rtm gemischt wurde * - * @param out ist der OutputStream, in den die gergten Daten geschickt werden sollen. - * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den - * Daten, die ins Template gemerged werden sollen. - * @param tmpl Name des Templates - * @exception ServletModuleException + * @param aRequest + * @param aResponse + * @throws ServletModuleExc + * @throws ServletModuleUserExc + * @throws ServletModuleFailure */ - private void deliver(HttpServletResponse res, HttpServletRequest req, PrintWriter out, - TemplateModelRoot rtm, String templateFilename) - throws ServletModuleFailure { + public void delete(HttpServletRequest aRequest, HttpServletResponse aResponse) + throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { try { - HTMLTemplateProcessor.process(res, templateFilename, rtm, null, out, getLocale(req), getFallbackLocale(req)); + String idParam = aRequest.getParameter("id"); + + if (idParam == null) + throw new ServletModuleExc("Invalid call to delete: no id supplied"); + + Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}); + + responseData.put("module", getOperationModuleName()); + responseData.put("id", idParam); + responseData.put("cancelurl", aRequest.getParameter("cancelurl")); + responseData.put("okurl", aRequest.getParameter("okurl")); + + ServletHelper.generateResponse(aResponse.getWriter(), responseData, deleteConfirmationGenerator); } catch (Throwable e) { throw new ServletModuleFailure(e); @@ -489,14 +493,14 @@ public abstract class ServletModule { * * @return Map with the values */ - public Map getIntersectingValues(HttpServletRequest req, StorageObject theStorage) + public Map getIntersectingValues(HttpServletRequest aRequest, StorageObject theStorage) throws ServletModuleExc, ServletModuleFailure { try { HTTPRequestParser parser; List theFieldList; - parser = new HTTPRequestParser(req); + parser = new HTTPRequestParser(aRequest); theFieldList = theStorage.getFields(); diff --git a/source/mir/servlet/ServletModuleDispatch.java b/source/mir/servlet/ServletModuleDispatch.java index 88435d0d..f5e841bb 100755 --- a/source/mir/servlet/ServletModuleDispatch.java +++ b/source/mir/servlet/ServletModuleDispatch.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.servlet; @@ -42,7 +42,7 @@ import mir.log.LoggerWrapper; * Dispatcher, calls the method passed to ServletModule Class, through the "do" * Parameter (via POST or GET) * - * @version $Id: ServletModuleDispatch.java,v 1.15 2003/04/21 12:42:50 idfx Exp $ + * @version $Id: ServletModuleDispatch.java,v 1.15.2.1 2003/09/03 17:49:38 zapata Exp $ * * @Author rk * @@ -52,56 +52,52 @@ public final class ServletModuleDispatch { private static LoggerWrapper logger = new LoggerWrapper("ServletModule.Dispatch"); private static final Class[] SIGNATURE = { HttpServletRequest.class, HttpServletResponse.class }; - /** - * private constructor to prevent unwanted instantiation; - */ + /** + * private parameter-less constructor to prevent unwanted instantiation + */ private ServletModuleDispatch () { } /** - * Die Dispatch-Routine ruft das von dem Hauptservlet kommende ServletModule - * mit dem per HttpServletRequest angegebenen Paramter do auf. - * Ist kein Parameter angegeben, so wird versucht, in die defaultAction - * des ServletModules zu springen. + * Method to dispatch servletmodule requests. * - * @param req Http-Request, das vom Dispatcher an die Methode des - * ServletModules durchgereicht wird - * @param res Http-Response, die vom Dispatcher an die Methode des - * ServletModules durchgereicht wird - * @param sMod ServletModule, an das dispatched wird. - * @param mod Name des Modules als String (f?r Logfile) + * @param aServletModule + * @param aRequest + * @param aResponse + * @throws ServletModuleExc + * @throws ServletModuleUserExc + * @throws ServletModuleFailure */ - public static void dispatch(ServletModule sMod, HttpServletRequest req, - HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure + public static void dispatch(ServletModule aServletModule, HttpServletRequest aRequest, + HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { - String doParam = req.getParameter("do"); - logger.info("ServletModuleDispatch: " + sMod.toString() + " with method " + doParam); + String doParam = aRequest.getParameter("do"); + logger.info("ServletModuleDispatch: " + aServletModule.toString() + " with method " + doParam); if (doParam == null) { - if (sMod.defaultAction() != null) - doParam = sMod.defaultAction(); + if (aServletModule.defaultAction() != null) + doParam = aServletModule.defaultAction(); else throw new ServletModuleExc("no parameter do supplied!"); } try { - Method method = sMod.getClass().getMethod(doParam,SIGNATURE); + Method method = aServletModule.getClass().getMethod(doParam,SIGNATURE); if (method != null) { - method.invoke(sMod,new Object[] {req,res} ); + method.invoke(aServletModule,new Object[] {aRequest,aResponse} ); return; } else logger.debug("method lookup unsuccesful"); } catch ( InvocationTargetException e) { - logger.error( "invocation target exception: " + e.getMessage()); + logger.error( "invocation target exception: " + e.toString()); e.getTargetException().printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); throw new ServletModuleFailure(e.getTargetException().getMessage(), e.getTargetException()); } catch (Throwable t) { - logger.error( "ServletModuleDispatch: " + t.getMessage()); - t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); + logger.error( "ServletModuleDispatch: " + t.toString()); throw new ServletModuleFailure(t); } } diff --git a/source/mir/servlet/ServletModuleShow.java b/source/mir/servlet/ServletModuleShow.java deleted file mode 100755 index 447f5f00..00000000 --- a/source/mir/servlet/ServletModuleShow.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with any library licensed under the Apache Software License, - * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library - * (or with modified versions of the above that use the same license as the above), - * and distribute linked combinations including the two. You must obey the - * GNU General Public License in all respects for all of the code used other than - * the above mentioned libraries. If you modify this file, you may extend this - * exception to your version of the file, but you are not obligated to do so. - * If you do not wish to do so, delete this exception statement from your version. - */ -package mir.servlet; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import freemarker.template.TemplateModelRoot; - - -/** - * Standard ServletModule, dass eine Template anzeigt, und nicht - * mit Daten mischt. Damit ist es moeglich, einfache HTML-Seiten - * als templates zu benutzen. Damit kann auf einfache Weise die - * Funktionalitaet der Freemarker-Bibliothek (beispielsweise Navigationen - * per include einzubauen) benutzt werden. Die Templates - * werden aus dem per Konfiguration angegebenem template-Verzeichnis - * im Ordner "/html" genommen. - * - * @author RK - */ -public class ServletModuleShow extends ServletModule { - private static ServletModuleShow instance = new ServletModuleShow(); - - /** - * Ein ServletModuleShow-Objekt wird ?ber getInstance geliefert. Es gibt zur - * Laufzeit nur ein Objekt (Singleton) - * @return ServletModuleShow - */ - public static ServletModule getInstance() { - return instance; - } - - /** - * Initialisierung leer. - */ - private ServletModuleShow() { - } - - /** - * defaultAction (s.a ServletModule) - * @return "show" - */ - public String defaultAction() { - return "show"; - } - - /** - * Standardmethode, die die Funktionalitaet des ServletModules implementiert. - * - * @param req Http-Request, das vom Dispatcher durchgereicht wird - * @param res Http-Response, die vom Dispatcher durchgereicht wird - * @return String fuer Logfile - * @exception ServletModuleException - */ - public void show(HttpServletRequest req, HttpServletResponse res) throws - ServletModuleExc { - try { - String idParam = req.getParameter("tmpl"); - if (! (idParam == null || idParam.equals(""))) { - deliver(req, res, (TemplateModelRoot)null, - "html/" + idParam + ".template"); - } - else { - throw new ServletModuleExc("Invalid template: " + idParam); - } - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } -} - - - - diff --git a/source/mir/storage/Database.java b/source/mir/storage/Database.java index 95be6616..e2a678e3 100755 --- a/source/mir/storage/Database.java +++ b/source/mir/storage/Database.java @@ -1,1601 +1,1459 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with any library licensed under the Apache Software License, - * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library - * (or with modified versions of the above that use the same license as the above), - * and distribute linked combinations including the two. You must obey the - * GNU General Public License in all respects for all of the code used other than - * the above mentioned libraries. If you modify this file, you may extend this - * exception to your version of the file, but you are not obligated to do so. - * If you do not wish to do so, delete this exception statement from your version. - */ -package mir.storage; - -import java.io.IOException; -import java.io.InputStreamReader; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Timestamp; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.*; -import java.util.Map; - -import com.codestudio.util.SQLManager; - -import freemarker.template.SimpleHash; -import freemarker.template.SimpleList; - -import mir.config.MirPropertiesConfiguration; -import mir.config.MirPropertiesConfiguration.PropertiesConfigExc; -import mir.entity.Entity; -import mir.entity.EntityList; -import mir.entity.StorableObjectEntity; -import mir.log.LoggerWrapper; -import mir.misc.HTMLTemplateProcessor; -import mir.misc.StringUtil; -import mir.storage.store.ObjectStore; -import mir.storage.store.StorableObject; -import mir.storage.store.StoreContainerType; -import mir.storage.store.StoreIdentifier; -import mir.storage.store.StoreUtil; -import mir.util.JDBCStringRoutines; - - -/** - * Diese Klasse implementiert die Zugriffsschicht auf die Datenbank. - * Alle Projektspezifischen Datenbankklassen erben von dieser Klasse. - * In den Unterklassen wird im Minimalfall nur die Tabelle angegeben. - * Im Konfigurationsfile findet sich eine Verweis auf den verwendeten - * Treiber, Host, User und Passwort, ueber den der Zugriff auf die - * Datenbank erfolgt. - * - * @version $Id: Database.java,v 1.44.2.5 2003/06/27 02:43:42 zapata Exp $ - * @author rk - * - */ -public class Database implements StorageObject { - private static Class GENERIC_ENTITY_CLASS = mir.entity.StorableObjectEntity.class; - private static Class STORABLE_OBJECT_ENTITY_CLASS = mir.entity.StorableObjectEntity.class; - - - private static SimpleHash POPUP_EMPTYLINE = new SimpleHash(); - protected static final ObjectStore o_store = ObjectStore.getInstance(); - private static final int _millisPerHour = 60 * 60 * 1000; - private static final int _millisPerMinute = 60 * 1000; - - static { - // always same object saves a little space - POPUP_EMPTYLINE.put("key", ""); - POPUP_EMPTYLINE.put("value", "--"); - } - - protected LoggerWrapper logger; - protected MirPropertiesConfiguration configuration; - protected String theTable; - protected String theCoreTable = null; - protected String thePKeyName = "id"; - protected int thePKeyType; - protected int thePKeyIndex; - protected boolean evaluatedMetaData = false; - protected ArrayList metadataFields; - protected ArrayList metadataLabels; - protected ArrayList metadataNotNullFields; - protected int[] metadataTypes; - protected Class theEntityClass; - protected SimpleList popupCache = null; - protected boolean hasPopupCache = false; - protected SimpleHash hashCache = null; - protected boolean hasTimestamp = true; - private String database_driver; - private String database_url; - private int defaultLimit; - - TimeZone timezone; - SimpleDateFormat internalDateFormat; - SimpleDateFormat userInputDateFormat; -/* - private SimpleDateFormat _dateFormatterOut; - private SimpleDateFormat _dateFormatterIn; - _dateFormatterOut = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - _dateFormatterIn = new SimpleDateFormat("yyyy-MM-dd HH:mm"); -*/ - - /** - * Kontruktor bekommt den Filenamen des Konfigurationsfiles ?bergeben. - * Aus diesem file werden Database.Logfile, - * Database.Username,Database.Password, - * Database.Host und Database.Adaptor - * ausgelesen und ein Broker f?r die Verbindugen zur Datenbank - * erzeugt. - * - * @param String confFilename Dateiname der Konfigurationsdatei - */ - public Database() throws StorageObjectFailure { - try { - configuration = MirPropertiesConfiguration.instance(); - } - catch (PropertiesConfigExc e) { - throw new StorageObjectFailure(e); - } - logger = new LoggerWrapper("Database"); - timezone = TimeZone.getTimeZone(configuration.getString("Mir.DefaultTimezone")); - internalDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - internalDateFormat.setTimeZone(timezone); - - userInputDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); - userInputDateFormat.setTimeZone(timezone); - - - String theAdaptorName = configuration.getString("Database.Adaptor"); - defaultLimit = Integer.parseInt(configuration.getString("Database.Limit")); - - try { - theEntityClass = GENERIC_ENTITY_CLASS; - } - catch (Throwable e) { - logger.error("Error in Database() constructor with " + theAdaptorName + " -- " + e.getMessage()); - throw new StorageObjectFailure("Error in Database() constructor.", e); - } - } - - /** - * Liefert die Entity-Klasse zur?ck, in der eine Datenbankzeile gewrappt - * wird. Wird die Entity-Klasse durch die erbende Klasse nicht ?berschrieben, - * wird eine mir.entity.GenericEntity erzeugt. - * - * @return Class-Objekt der Entity - */ - public java.lang.Class getEntityClass() { - return theEntityClass; - } - - /** - * Liefert die Standardbeschr?nkung von select-Statements zur?ck, also - * wieviel Datens?tze per Default selektiert werden. - * - * @return Standard-Anzahl der Datens?tze - */ - public int getLimit() { - return defaultLimit; - } - - /** - * Liefert den Namen des Primary-Keys zur?ck. Wird die Variable nicht von - * der erbenden Klasse ?berschrieben, so ist der Wert PKEY - * @return Name des Primary-Keys - */ - public String getIdName() { - return thePKeyName; - } - - /** - * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht. - * - * @return Name der Tabelle - */ - public String getTableName() { - return theTable; - } - - /* - * Dient dazu vererbte Tabellen bei objectrelationalen DBMS - * zu speichern, wenn die id einer Tabelle in der parenttabelle verwaltet - * wird. - * @return liefert theCoreTabel als String zurueck, wenn gesetzt, sonst - * the Table - */ - public String getCoreTable() { - if (theCoreTable != null) { - return theCoreTable; - } - else { - return theTable; - } - } - - /** - * Liefert Feldtypen der Felder der Tabelle zurueck (s.a. java.sql.Types) - * @return int-Array mit den Typen der Felder - * @exception StorageObjectException - */ - public int[] getTypes() throws StorageObjectFailure { - if (metadataTypes == null) { - get_meta_data(); - } - - return metadataTypes; - } - - /** - * Liefert eine Liste der Labels der Tabellenfelder - * @return ArrayListe mit Labeln - * @exception StorageObjectException - */ - public List getLabels() throws StorageObjectFailure { - if (metadataLabels == null) { - get_meta_data(); - } - - return metadataLabels; - } - - /** - * Liefert eine Liste der Felder der Tabelle - * @return ArrayList mit Feldern - * @exception StorageObjectException - */ - public List getFields() throws StorageObjectFailure { - if (metadataFields == null) { - get_meta_data(); - } - - return metadataFields; - } - - /* - * Gets value out of ResultSet according to type and converts to String - * @param inValue Wert aus ResultSet. - * @param aType Datenbanktyp. - * @return liefert den Wert als String zurueck. Wenn keine Umwandlung moeglich - * dann /unsupported value/ - */ - private String getValueAsString(ResultSet rs, int valueIndex, int aType) - throws StorageObjectFailure { - String outValue = null; - - if (rs != null) { - try { - switch (aType) { - case java.sql.Types.BIT: - outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0"; - - break; - - case java.sql.Types.INTEGER: - case java.sql.Types.SMALLINT: - case java.sql.Types.TINYINT: - case java.sql.Types.BIGINT: - - int out = rs.getInt(valueIndex); - - if (!rs.wasNull()) { - outValue = new Integer(out).toString(); - } - - break; - - case java.sql.Types.NUMERIC: - - /** @todo Numeric can be float or double depending upon - * metadata.getScale() / especially with oracle */ - long outl = rs.getLong(valueIndex); - - if (!rs.wasNull()) { - outValue = new Long(outl).toString(); - } - - break; - - case java.sql.Types.REAL: - - float tempf = rs.getFloat(valueIndex); - - if (!rs.wasNull()) { - tempf *= 10; - tempf += 0.5; - - int tempf_int = (int) tempf; - tempf = (float) tempf_int; - tempf /= 10; - outValue = "" + tempf; - outValue = outValue.replace('.', ','); - } - - break; - - case java.sql.Types.DOUBLE: - - double tempd = rs.getDouble(valueIndex); - - if (!rs.wasNull()) { - tempd *= 10; - tempd += 0.5; - - int tempd_int = (int) tempd; - tempd = (double) tempd_int; - tempd /= 10; - outValue = "" + tempd; - outValue = outValue.replace('.', ','); - } - - break; - - case java.sql.Types.CHAR: - case java.sql.Types.VARCHAR: - case java.sql.Types.LONGVARCHAR: - outValue = rs.getString(valueIndex); - - break; - - case java.sql.Types.LONGVARBINARY: - outValue = rs.getString(valueIndex); - - break; - - case java.sql.Types.TIMESTAMP: - - // it's important to use Timestamp here as getting it - // as a string is undefined and is only there for debugging - // according to the API. we can make it a string through formatting. - // -mh - Timestamp timestamp = (rs.getTimestamp(valueIndex)); - - if (!rs.wasNull()) { - java.util.Date date = new java.util.Date(timestamp.getTime()); - - Calendar calendar = new GregorianCalendar(); - calendar.setTime(date); - calendar.setTimeZone(timezone); - outValue = internalDateFormat.format(date); - - int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET); - String tzOffset = StringUtil.zeroPaddingNumber(Math.abs(offset) / _millisPerHour, 2, 2); - - if (offset<0) - outValue = outValue + "-"; - else - outValue = outValue + "+"; - outValue = outValue + tzOffset; - } - - break; - - default: - outValue = ""; - logger.warn("Unsupported Datatype: at " + valueIndex + " (" + aType + ")"); - } - } catch (SQLException e) { - throw new StorageObjectFailure("Could not get Value out of Resultset -- ", - e); - } - } - - return outValue; - } - - /* - * select-Operator um einen Datensatz zu bekommen. - * @param id Primaerschluessel des Datensatzes. - * @return liefert EntityObject des gefundenen Datensatzes oder null. - */ - public Entity selectById(String id) throws StorageObjectExc { - if ((id == null) || id.equals("")) { - throw new StorageObjectExc("Database.selectById: Missing id"); - } - - // ask object store for object - if (StoreUtil.implementsStorableObject(theEntityClass)) { - String uniqueId = id; - - if (theEntityClass.equals(StorableObjectEntity.class)) { - uniqueId += ("@" + theTable); - } - - StoreIdentifier search_sid = new StoreIdentifier(theEntityClass, uniqueId); - logger.debug("CACHE: (dbg) looking for sid " + search_sid.toString()); - - Entity hit = (Entity) o_store.use(search_sid); - - if (hit != null) { - return hit; - } - } - - Statement stmt = null; - Connection con = getPooledCon(); - Entity returnEntity = null; - - try { - ResultSet rs; - - /** @todo better prepared statement */ - String selectSql = - "select * from " + theTable + " where " + thePKeyName + "=" + id; - stmt = con.createStatement(); - rs = executeSql(stmt, selectSql); - - if (rs != null) { - if (evaluatedMetaData == false) { - evalMetaData(rs.getMetaData()); - } - - if (rs.next()) { - returnEntity = makeEntityFromResultSet(rs); - } - else { - logger.debug("No data for id: " + id + " in table " + theTable); - } - - rs.close(); - } - else { - logger.debug("No Data for Id " + id + " in Table " + theTable); - } - } - catch (SQLException sqe) { - throwSQLException(sqe, "selectById"); - return null; - } - catch (NumberFormatException e) { - logger.error("ID is no number: " + id); - } - finally { - freeConnection(con, stmt); - } - - return returnEntity; - } - - /** - * select-Operator um Datensaetze zu bekommen, die key = value erfuellen. - * @param key Datenbankfeld der Bedingung. - * @param value Wert die der key anehmen muss. - * @return EntityList mit den gematchten Entities - */ - public EntityList selectByFieldValue(String aField, String aValue) throws StorageObjectFailure { - return selectByFieldValue(aField, aValue, 0); - } - - /** - * select-Operator um Datensaetze zu bekommen, die key = value erfuellen. - * @param key Datenbankfeld der Bedingung. - * @param value Wert die der key anehmen muss. - * @param offset Gibt an ab welchem Datensatz angezeigt werden soll. - * @return EntityList mit den gematchten Entities - */ - public EntityList selectByFieldValue(String aField, String aValue, int offset) throws StorageObjectFailure { - return selectByWhereClause(aField + "=" + aValue, offset); - } - - /** - * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. - * Also offset wird der erste Datensatz genommen. - * - * @param wc where-Clause - * @return EntityList mit den gematchten Entities - * @exception StorageObjectException - */ - public EntityList selectByWhereClause(String where) throws StorageObjectFailure { - return selectByWhereClause(where, 0); - } - - /** - * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. - * Als maximale Anzahl wird das Limit auf der Konfiguration genommen. - * - * @param wc where-Clause - * @param offset ab welchem Datensatz. - * @return EntityList mit den gematchten Entities - * @exception StorageObjectException - */ - public EntityList selectByWhereClause(String whereClause, int offset) throws StorageObjectFailure { - return selectByWhereClause(whereClause, null, offset); - } - - /** - * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. - * Also offset wird der erste Datensatz genommen. - * Als maximale Anzahl wird das Limit auf der Konfiguration genommen. - * - * @param wc where-Clause - * @param ob orderBy-Clause - * @return EntityList mit den gematchten Entities - * @exception StorageObjectException - */ - public EntityList selectByWhereClause(String where, String order) throws StorageObjectFailure { - return selectByWhereClause(where, order, 0); - } - - /** - * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. - * Als maximale Anzahl wird das Limit auf der Konfiguration genommen. - * - * @param wc where-Clause - * @param ob orderBy-Clause - * @param offset ab welchem Datensatz - * @return EntityList mit den gematchten Entities - * @exception StorageObjectException - */ - public EntityList selectByWhereClause(String whereClause, String orderBy, int offset) throws StorageObjectFailure { - return selectByWhereClause(whereClause, orderBy, offset, defaultLimit); - } - - /** - * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. - * @param aWhereClause where-Clause - * @param anOrderByClause orderBy-Clause - * @param offset ab welchem Datensatz - * @param limit wieviele Datens?tze - * @return EntityList mit den gematchten Entities - * @exception StorageObjectException - */ - public EntityList selectByWhereClause(String aWhereClause, String anOrderByClause, - int offset, int limit) throws StorageObjectFailure { - - // check o_store for entitylist - if (StoreUtil.implementsStorableObject(theEntityClass)) { - StoreIdentifier search_sid = - new StoreIdentifier( - theEntityClass, StoreContainerType.STOC_TYPE_ENTITYLIST, - StoreUtil.getEntityListUniqueIdentifierFor(theTable, aWhereClause, anOrderByClause, offset, limit)); - EntityList hit = (EntityList) o_store.use(search_sid); - - if (hit != null) { - logger.debug("CACHE (hit): " + search_sid.toString()); - - return hit; - } - } - - // local - EntityList theReturnList = null; - Connection con = null; - Statement stmt = null; - ResultSet rs; - int offsetCount = 0; - int count = 0; - - // build sql-statement - - /** @todo count sql string should only be assembled if we really count - * see below at the end of method //rk */ - if ((aWhereClause != null) && (aWhereClause.trim().length() == 0)) { - aWhereClause = null; - } - - StringBuffer countSql = - new StringBuffer("select count(*) from ").append(theTable); - StringBuffer selectSql = - new StringBuffer("select * from ").append(theTable); - - if (aWhereClause != null) { - selectSql.append(" where ").append(aWhereClause); - countSql.append(" where ").append(aWhereClause); - } - - if ((anOrderByClause != null) && !(anOrderByClause.trim().length() == 0)) { - selectSql.append(" order by ").append(anOrderByClause); - } - - if ((limit > -1) && (offset > -1)) { - selectSql.append(" LIMIT ").append(limit).append(" OFFSET ").append(offset); - } - - // execute sql - try { - con = getPooledCon(); - stmt = con.createStatement(); - - // selecting... - rs = executeSql(stmt, selectSql.toString()); - - if (rs != null) { - if (!evaluatedMetaData) { - evalMetaData(rs.getMetaData()); - } - - theReturnList = new EntityList(); - - Entity theResultEntity; - - while (rs.next()) { - theResultEntity = makeEntityFromResultSet(rs); - theReturnList.add(theResultEntity); - offsetCount++; - } - - rs.close(); - } - - // making entitylist infos - count = offsetCount; - - if (theReturnList != null) { - // now we decide if we have to know an overall count... - count = offsetCount; - - if ((limit > -1) && (offset > -1)) { - if (offsetCount == limit) { - /** @todo counting should be deffered to entitylist - * getSize() should be used */ - rs = executeSql(stmt, countSql.toString()); - - if (rs != null) { - if (rs.next()) { - count = rs.getInt(1); - } - - rs.close(); - } - else { - logger.error("Could not count: " + countSql); - } - } - } - - theReturnList.setCount(count); - theReturnList.setOffset(offset); - theReturnList.setWhere(aWhereClause); - theReturnList.setOrder(anOrderByClause); - theReturnList.setStorage(this); - theReturnList.setLimit(limit); - - if (offset >= limit) { - theReturnList.setPrevBatch(offset - limit); - } - - if ((offset + offsetCount) < count) { - theReturnList.setNextBatch(offset + limit); - } - - if (StoreUtil.implementsStorableObject(theEntityClass)) { - StoreIdentifier sid = theReturnList.getStoreIdentifier(); - logger.debug("CACHE (add): " + sid.toString()); - o_store.add(sid); - } - } - } - catch (SQLException sqe) { - throwSQLException(sqe, "selectByWhereClause"); - } - finally { - try { - if (con != null) { - freeConnection(con, stmt); - } - } catch (Throwable t) { - } - } - - return theReturnList; - } - - /** - * Bastelt aus einer Zeile der Datenbank ein EntityObjekt. - * - * @param rs Das ResultSetObjekt. - * @return Entity Die Entity. - */ - private Entity makeEntityFromResultSet(ResultSet rs) - throws StorageObjectFailure { - /** @todo OS: get Pkey from ResultSet and consult ObjectStore */ - Map theResultHash = new HashMap(); - String theResult = null; - int theType; - Entity returnEntity = null; - - try { - int size = metadataFields.size(); - - for (int i = 0; i < size; i++) { - // alle durchlaufen bis nix mehr da - theType = metadataTypes[i]; - - if (theType == java.sql.Types.LONGVARBINARY) { - InputStreamReader is = - (InputStreamReader) rs.getCharacterStream(i + 1); - - if (is != null) { - char[] data = new char[32768]; - StringBuffer theResultString = new StringBuffer(); - int len; - - while ((len = is.read(data)) > 0) { - theResultString.append(data, 0, len); - } - - is.close(); - theResult = theResultString.toString(); - } else { - theResult = null; - } - } else { - theResult = getValueAsString(rs, (i + 1), theType); - } - - if (theResult != null) { - theResultHash.put(metadataFields.get(i), theResult); - } - } - - if (theEntityClass != null) { - returnEntity = (Entity) theEntityClass.newInstance(); - returnEntity.setStorage(this); - returnEntity.setValues(theResultHash); - - if (returnEntity instanceof StorableObject) { - logger.debug("CACHE: ( in) " + returnEntity.getId() + " :" + theTable); - o_store.add(((StorableObject) returnEntity).getStoreIdentifier()); - } - } else { - throwStorageObjectException("Internal Error: theEntityClass not set!"); - } - } - catch (IllegalAccessException e) { - throwStorageObjectException("No access! -- " + e.getMessage()); - } - catch (IOException e) { - throwStorageObjectException("IOException! -- " + e.getMessage()); - } - catch (InstantiationException e) { - throwStorageObjectException("No Instatiation! -- " + e.getMessage()); - } - catch (SQLException sqe) { - throwSQLException(sqe, "makeEntityFromResultSet"); - - return null; - } - - return returnEntity; - } - - /** - * Inserts an entity into the database. - * - * @param theEntity - * @return der Wert des Primary-keys der eingef?gten Entity - */ - public String insert(Entity theEntity) throws StorageObjectFailure { - //cache - invalidatePopupCache(); - - // invalidating all EntityLists corresponding with theEntityClass - if (StoreUtil.implementsStorableObject(theEntityClass)) { - StoreContainerType stoc_type = - StoreContainerType.valueOf(theEntityClass, - StoreContainerType.STOC_TYPE_ENTITYLIST); - o_store.invalidate(stoc_type); - } - - String returnId = null; - Connection con = null; - PreparedStatement pstmt = null; - - try { - List streamedInput = theEntity.streamedInput(); - StringBuffer f = new StringBuffer(); - StringBuffer v = new StringBuffer(); - String aField; - String aValue; - boolean firstField = true; - - // make sql-string - for (int i = 0; i < getFields().size(); i++) { - aField = (String) getFields().get(i); - - if (!aField.equals(thePKeyName)) { - aValue = null; - - // exceptions - if (!theEntity.hasValueForField(aField) && ( - aField.equals("webdb_create") || - aField.equals("webdb_lastchange"))) { - aValue = "NOW()"; - } - else { - if ((streamedInput != null) && streamedInput.contains(aField)) { - aValue = "?"; - } - else { - if (theEntity.hasValueForField(aField)) { - aValue = - "'" + - JDBCStringRoutines.escapeStringLiteral((String) theEntity.getValue(aField)) + "'"; - } - } - } - - // wenn Wert gegeben, dann einbauen - if (aValue != null) { - if (firstField == false) { - f.append(","); - v.append(","); - } - else { - firstField = false; - } - - f.append(aField); - v.append(aValue); - } - } - } - // end for - - // insert into db - StringBuffer sqlBuf = - new StringBuffer("insert into ").append(theTable).append("(").append(f) - .append(") values (").append(v).append(")"); - String sql = sqlBuf.toString(); - - logger.debug("INSERT: " + sql); - con = getPooledCon(); - con.setAutoCommit(false); - pstmt = con.prepareStatement(sql); - - if (streamedInput != null) { - for (int i = 0; i < streamedInput.size(); i++) { - String inputString = - (String) theEntity.getValue((String) streamedInput.get(i)); - pstmt.setBytes(i + 1, inputString.getBytes()); - } - } - - int ret = pstmt.executeUpdate(); - - if (ret == 0) { - //insert failed - return null; - } - - pstmt = con.prepareStatement("select currval('" + getCoreTable() + "_id_seq')"); - - ResultSet rs = pstmt.executeQuery(); - rs.next(); - returnId = rs.getString(1); - theEntity.setId(returnId); - } - catch (SQLException sqe) { - throwSQLException(sqe, "insert"); - } - finally { - try { - con.setAutoCommit(true); - } - catch (Exception e) { - } - - freeConnection(con, pstmt); - } - - /** @todo store entity in o_store */ - return returnId; - } - - /** - * Updates an entity in the database - * - * @param theEntity - */ - public void update(Entity theEntity) throws StorageObjectFailure { - Connection con = null; - PreparedStatement pstmt = null; - - /** @todo this is stupid: why do we prepare statement, when we - * throw it away afterwards. should be regular statement - * update/insert could better be one routine called save() - * that chooses to either insert or update depending if we - * have a primary key in the entity. i don't know if we - * still need the streamed input fields. // rk */ - /** @todo extension: check if Entity did change, otherwise we don't need - * the roundtrip to the database */ - /** invalidating corresponding entitylists in o_store*/ - if (StoreUtil.implementsStorableObject(theEntityClass)) { - StoreContainerType stoc_type = - StoreContainerType.valueOf(theEntityClass, - StoreContainerType.STOC_TYPE_ENTITYLIST); - o_store.invalidate(stoc_type); - } - - List streamedInput = theEntity.streamedInput(); - String id = theEntity.getId(); - String aField; - StringBuffer fv = new StringBuffer(); - boolean firstField = true; - - //cache - invalidatePopupCache(); - - // build sql statement - for (int i = 0; i < getFields().size(); i++) { - aField = (String) metadataFields.get(i); - - // only normal cases - if ( !(aField.equals(thePKeyName) || - aField.equals("webdb_create") || - aField.equals("webdb_lastchange") || - ((streamedInput != null) && streamedInput.contains(aField)))) { - if (theEntity.hasValueForField(aField)) { - if (firstField == false) { - fv.append(", "); - } - else { - firstField = false; - } - - fv.append(aField).append("='").append(JDBCStringRoutines.escapeStringLiteral((String) theEntity.getValue(aField))).append("'"); - - // fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'"); - } - } - } - - StringBuffer sql = - new StringBuffer("update ").append(theTable).append(" set ").append(fv); - - // exceptions - if (metadataFields.contains("webdb_lastchange")) { - sql.append(",webdb_lastchange=NOW()"); - } - - // special case: the webdb_create requires the field in yyyy-mm-dd HH:mm - // format so anything extra will be ignored. -mh - if (metadataFields.contains("webdb_create") && - theEntity.hasValueForField("webdb_create")) { - // minimum of 10 (yyyy-mm-dd)... - if (theEntity.getValue("webdb_create").length() >= 10) { - String dateString = theEntity.getValue("webdb_create"); - - // if only 10, then add 00:00 so it doesn't throw a ParseException - if (dateString.length() == 10) { - dateString = dateString + " 00:00"; - } - - // TimeStamp stuff - try { - java.util.Date d = userInputDateFormat.parse(dateString); -// Timestamp tStamp = new Timestamp(d.getTime()); - sql.append(",webdb_create='" + JDBCStringRoutines.formatDate(d) + "'"); - } - catch (ParseException e) { - throw new StorageObjectFailure(e); - } - } - } - - if (streamedInput != null) { - for (int i = 0; i < streamedInput.size(); i++) { - sql.append(",").append(streamedInput.get(i)).append("=?"); - } - } - - sql.append(" where id=").append(id); - logger.debug("UPDATE: " + sql); - - try { - con = getPooledCon(); - con.setAutoCommit(false); - pstmt = con.prepareStatement(sql.toString()); - - if (streamedInput != null) { - for (int i = 0; i < streamedInput.size(); i++) { - String inputString = - theEntity.getValue((String) streamedInput.get(i)); - pstmt.setBytes(i + 1, inputString.getBytes()); - } - } - - pstmt.executeUpdate(); - } - catch (SQLException sqe) { - throwSQLException(sqe, "update"); - } - finally { - try { - con.setAutoCommit(true); - } - catch (Exception e) { - ; - } - - freeConnection(con, pstmt); - } - } - - /* - * delete-Operator - * @param id des zu loeschenden Datensatzes - * @return boolean liefert true zurueck, wenn loeschen erfolgreich war. - */ - public boolean delete(String id) throws StorageObjectFailure { - invalidatePopupCache(); - - // ostore send notification - if (StoreUtil.implementsStorableObject(theEntityClass)) { - String uniqueId = id; - - if (theEntityClass.equals(StorableObjectEntity.class)) { - uniqueId += ("@" + theTable); - } - - logger.debug("CACHE: (del) " + id); - - StoreIdentifier search_sid = - new StoreIdentifier(theEntityClass, - StoreContainerType.STOC_TYPE_ENTITY, uniqueId); - o_store.invalidate(search_sid); - } - - /** @todo could be prepared Statement */ - Statement stmt = null; - Connection con = null; - int res = 0; - String sql = - "delete from " + theTable + " where " + thePKeyName + "='" + id + "'"; - - //theLog.printInfo("DELETE " + sql); - try { - con = getPooledCon(); - stmt = con.createStatement(); - res = stmt.executeUpdate(sql); - } catch (SQLException sqe) { - throwSQLException(sqe, "delete"); - } finally { - freeConnection(con, stmt); - } - - return (res > 0) ? true : false; - } - - /** - * Deletes entities based on a where clause - * - * @param aWhereClause - * @return - * @throws StorageObjectFailure - */ - public int deleteByWhereClause(String aWhereClause) throws StorageObjectFailure { - invalidatePopupCache(); - if (StoreUtil.implementsStorableObject(theEntityClass)) { - StoreContainerType stoc_type = StoreContainerType.valueOf(theEntityClass, StoreContainerType.STOC_TYPE_ENTITYLIST); - o_store.invalidate(stoc_type); - } - - Statement stmt = null; - Connection con = null; - int res = 0; - String sql = - "delete from " + theTable + " where " + aWhereClause; - - //theLog.printInfo("DELETE " + sql); - try { - con = getPooledCon(); - stmt = con.createStatement(); - res = stmt.executeUpdate(sql); - } - catch (SQLException sqe) { - throwSQLException(sqe, "delete"); - } - finally { - freeConnection(con, stmt); - } - - return res; - } - - /* noch nicht implementiert. - * @return immer false - */ - public boolean delete(EntityList theEntityList) { - invalidatePopupCache(); - - return false; - } - - /** - * Diese Methode sollte ueberschrieben werden, wenn fuer die abgeleitete Database-Klasse - * eine SimpleList mit Standard-Popupdaten erzeugt werden koennen soll. - * @return null - */ - public SimpleList getPopupData() throws StorageObjectFailure { - return null; - } - - /** - * Holt Daten fuer Popups. - * @param name Name des Feldes. - * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt. - * @return SimpleList Gibt freemarker.template.SimpleList zurueck. - */ - public SimpleList getPopupData(String name, boolean hasNullValue) - throws StorageObjectFailure { - return getPopupData(name, hasNullValue, null); - } - - /** - * Holt Daten fuer Popups. - * @param name Name des Feldes. - * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt. - * @param where Schraenkt die Selektion der Datensaetze ein. - * @return SimpleList Gibt freemarker.template.SimpleList zurueck. - */ - public SimpleList getPopupData(String name, boolean hasNullValue, String where) - throws StorageObjectFailure { - return getPopupData(name, hasNullValue, where, null); - } - - /** - * Holt Daten fuer Popups. - * @param name Name des Feldes. - * @param hasNullValue Wenn true wird eine leerer Eintrag fuer die Popups erzeugt. - * @param where Schraenkt die Selektion der Datensaetze ein. - * @param order Gibt ein Feld als Sortierkriterium an. - * @return SimpleList Gibt freemarker.template.SimpleList zurueck. - */ - public SimpleList getPopupData(String name, boolean hasNullValue, - String where, String order) throws StorageObjectFailure { - // caching - if (hasPopupCache && (popupCache != null)) { - return popupCache; - } - - SimpleList simpleList = null; - Connection con = null; - Statement stmt = null; - - // build sql - StringBuffer sql = - new StringBuffer("select ").append(thePKeyName).append(",").append(name) - .append(" from ").append(theTable); - - if ((where != null) && !(where.length() == 0)) { - sql.append(" where ").append(where); - } - - sql.append(" order by "); - - if ((order != null) && !(order.length() == 0)) { - sql.append(order); - } else { - sql.append(name); - } - - // execute sql - try { - con = getPooledCon(); - } catch (Exception e) { - throw new StorageObjectFailure(e); - } - - try { - stmt = con.createStatement(); - - ResultSet rs = executeSql(stmt, sql.toString()); - - if (rs != null) { - if (!evaluatedMetaData) { - get_meta_data(); - } - - simpleList = new SimpleList(); - - // if popup has null-selector - if (hasNullValue) { - simpleList.add(POPUP_EMPTYLINE); - } - - SimpleHash popupDict; - - while (rs.next()) { - popupDict = new SimpleHash(); - popupDict.put("key", getValueAsString(rs, 1, thePKeyType)); - popupDict.put("value", rs.getString(2)); - simpleList.add(popupDict); - } - - rs.close(); - } - } - catch (Exception e) { - logger.error("getPopupData: " + e.getMessage()); - throw new StorageObjectFailure(e); - } finally { - freeConnection(con, stmt); - } - - if (hasPopupCache) { - popupCache = simpleList; - } - - return simpleList; - } - - /** - * Liefert alle Daten der Tabelle als SimpleHash zurueck. Dies wird verwandt, - * wenn in den Templates ein Lookup-Table benoetigt wird. Sollte nur bei kleinen - * Tabellen Verwendung finden. - * @return SimpleHash mit den Tabellezeilen. - */ - public SimpleHash getHashData() { - /** @todo dangerous! this should have a flag to be enabled, otherwise - * very big Hashes could be returned */ - if (hashCache == null) { - try { - hashCache = - HTMLTemplateProcessor.makeSimpleHash(selectByWhereClause("", -1)); - } - catch (StorageObjectFailure e) { - logger.debug(e.getMessage()); - } - } - - return hashCache; - } - - /* invalidates the popupCache - */ - protected void invalidatePopupCache() { - /** @todo invalidates toooo much */ - popupCache = null; - hashCache = null; - } - - /** - * Diese Methode fuehrt den Sqlstring sql aus und timed im Logfile. - * @param stmt Statemnt - * @param sql Sql-String - * @return ResultSet - * @exception StorageObjectException - */ - public ResultSet executeSql(Statement stmt, String sql) - throws StorageObjectFailure, SQLException { - ResultSet rs; - long startTime = System.currentTimeMillis(); - - try { - rs = stmt.executeQuery(sql); - - logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql); - } - catch (SQLException e) { - logger.error(e.getMessage() +"\n" + (System.currentTimeMillis() - startTime) + "ms. for: " + sql); - throw e; - } - - return rs; - } -/* - public ResultSet executeSql(String sql) throws StorageObjectFailure, SQLException { - long startTime = System.currentTimeMillis(); - Connection connection = null; - Statement statement = null; - - try { - connection = getPooledCon(); - statement = connection.createStatement(); - ResultSet result; - - result = statement.executeQuery(sql); - - logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql); - return result; - } - catch (Throwable e) { - logger.error(e.getMessage() +"\n" + (System.currentTimeMillis() - startTime) + "ms. for: " + sql); - throw new StorageObjectFailure(e); - } - finally { - if (connection!=null) { - freeConnection(connection, statement); - } - } - } -*/ - private Map processRow(ResultSet aResultSet) throws StorageObjectFailure, StorageObjectExc { - try { - Map result = new HashMap(); - ResultSetMetaData metaData = aResultSet.getMetaData(); - int nrColumns = metaData.getColumnCount(); - for (int i=0; i0) - return (Map) resultList.get(0); - else - return null; - } - finally { - } - } - catch (Throwable t) { - throw new StorageObjectFailure(t); - } - }; - - public String executeFreeSingleValueSql(String sql) throws StorageObjectFailure, StorageObjectExc { - Map row = executeFreeSingleRowSql(sql); - - if (row==null) - return null; - - Iterator i = row.values().iterator(); - if (i.hasNext()) - return (String) i.next(); - else - return null; - }; - - /** - * returns the number of rows in the table - */ - public int getSize(String where) throws SQLException, StorageObjectFailure { - long startTime = System.currentTimeMillis(); - String sql = "SELECT Count(*) FROM " + theTable; - - if ((where != null) && (where.length() != 0)) { - sql = sql + " where " + where; - } - - Connection con = null; - Statement stmt = null; - int result = 0; - - try { - con = getPooledCon(); - stmt = con.createStatement(); - - ResultSet rs = executeSql(stmt, sql); - - while (rs.next()) { - result = rs.getInt(1); - } - } - catch (SQLException e) { - logger.error("Database.getSize: " + e.getMessage()); - } - finally { - freeConnection(con, stmt); - } - - //theLog.printInfo(theTable + " has "+ result +" rows where " + where); - logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql); - - return result; - } - - public int executeUpdate(Statement stmt, String sql) - throws StorageObjectFailure, SQLException { - int rs; - long startTime = System.currentTimeMillis(); - - try { - rs = stmt.executeUpdate(sql); - - logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql); - } - catch (SQLException e) { - logger.error("Failed: " + (System.currentTimeMillis() - startTime) + "ms. for: " + sql); - throw e; - } - - return rs; - } - - public int executeUpdate(String sql) - throws StorageObjectFailure, SQLException { - int result = -1; - long startTime = System.currentTimeMillis(); - Connection con = null; - PreparedStatement pstmt = null; - - try { - con = getPooledCon(); - pstmt = con.prepareStatement(sql); - result = pstmt.executeUpdate(); - } - catch (Throwable e) { - logger.error("Database.executeUpdate(" + sql + "): " + e.getMessage()); - throw new StorageObjectFailure("Database.executeUpdate(" + sql + "): " + e.getMessage(), e); - } - finally { - freeConnection(con, pstmt); - } - - logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql); - return result; - } - - /** - * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend - * @param md ResultSetMetaData - * @exception StorageObjectException - */ - private void evalMetaData(ResultSetMetaData md) throws StorageObjectFailure { - this.evaluatedMetaData = true; - this.metadataFields = new ArrayList(); - this.metadataLabels = new ArrayList(); - this.metadataNotNullFields = new ArrayList(); - - try { - int numFields = md.getColumnCount(); - this.metadataTypes = new int[numFields]; - - String aField; - int aType; - - for (int i = 1; i <= numFields; i++) { - aField = md.getColumnName(i); - metadataFields.add(aField); - metadataLabels.add(md.getColumnLabel(i)); - aType = md.getColumnType(i); - metadataTypes[i - 1] = aType; - - if (aField.equals(thePKeyName)) { - thePKeyType = aType; - thePKeyIndex = i; - } - - if (md.isNullable(i) == ResultSetMetaData.columnNullable) { - metadataNotNullFields.add(aField); - } - } - } - catch (SQLException e) { - throwSQLException(e, "evalMetaData"); - } - } - - /** - * Wertet die Metadaten eines Resultsets fuer eine Tabelle aus, - * um die alle Columns und Typen einer Tabelle zu ermitteln. - */ - private void get_meta_data() throws StorageObjectFailure { - Connection con = null; - PreparedStatement pstmt = null; - String sql = "select * from " + theTable + " where 0=1"; - - try { - con = getPooledCon(); - pstmt = con.prepareStatement(sql); - - logger.debug("METADATA: " + sql); - ResultSet rs = pstmt.executeQuery(); - evalMetaData(rs.getMetaData()); - rs.close(); - } - catch (SQLException e) { - throwSQLException(e, "get_meta_data"); - } - finally { - freeConnection(con, pstmt); - } - } - - public Connection getPooledCon() throws StorageObjectFailure { - Connection con = null; - - try { - con = SQLManager.getInstance().requestConnection(); - } - catch (SQLException e) { - logger.error("could not connect to the database " + e.getMessage()); - - throw new StorageObjectFailure("Could not connect to the database", e); - } - - return con; - } - - public void freeConnection(Connection con, Statement stmt) - throws StorageObjectFailure { - SQLManager.closeStatement(stmt); - SQLManager.getInstance().returnConnection(con); - } - - /** - * Wertet SQLException aus und wirft dannach eine StorageObjectException - * @param sqe SQLException - * @param wo Funktonsname, in der die SQLException geworfen wurde - * @exception StorageObjectException - */ - protected void throwSQLException(SQLException sqe, String aFunction) throws StorageObjectFailure { - String state = ""; - String message = ""; - int vendor = 0; - - if (sqe != null) { - state = sqe.getSQLState(); - message = sqe.getMessage(); - vendor = sqe.getErrorCode(); - } - - String information = - "SQL Error: " + - "state= " + state + - ", vendor= " + vendor + - ", message=" + message + - ", function= " + aFunction; - - logger.error(information); - - throw new StorageObjectFailure(information, sqe); - } - - protected void _throwStorageObjectException(Exception e, String aFunction) - throws StorageObjectFailure { - - if (e != null) { - logger.error(e.getMessage() + aFunction); - throw new StorageObjectFailure(aFunction, e); - } - } - - /** - * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach - * eine StorageObjectException - * @param message Nachricht mit dem Fehler - * @exception StorageObjectException - */ - void throwStorageObjectException(String aMessage) throws StorageObjectFailure { - logger.error(aMessage); - throw new StorageObjectFailure(aMessage, null); - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, but you are not obligated to do so. + * If you do not wish to do so, delete this exception statement from your version. + */ +package mir.storage; + +import java.io.IOException; +import java.io.InputStreamReader; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.sql.Timestamp; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.TimeZone; +import java.util.Vector; + +import com.codestudio.util.SQLManager; +import mir.config.MirPropertiesConfiguration; +import mir.config.MirPropertiesConfiguration.PropertiesConfigExc; +import mir.entity.Entity; +import mir.entity.EntityList; +import mir.entity.StorableObjectEntity; +import mir.log.LoggerWrapper; +import mir.misc.StringUtil; +import mir.storage.store.ObjectStore; +import mir.storage.store.StorableObject; +import mir.storage.store.StoreContainerType; +import mir.storage.store.StoreIdentifier; +import mir.storage.store.StoreUtil; +import mir.util.JDBCStringRoutines; + + +/** + * Diese Klasse implementiert die Zugriffsschicht auf die Datenbank. + * Alle Projektspezifischen Datenbankklassen erben von dieser Klasse. + * In den Unterklassen wird im Minimalfall nur die Tabelle angegeben. + * Im Konfigurationsfile findet sich eine Verweis auf den verwendeten + * Treiber, Host, User und Passwort, ueber den der Zugriff auf die + * Datenbank erfolgt. + * + * @version $Id: Database.java,v 1.44.2.6 2003/09/03 17:49:39 zapata Exp $ + * @author rk + * + */ +public class Database implements StorageObject { + private static Class GENERIC_ENTITY_CLASS = mir.entity.StorableObjectEntity.class; + private static Class STORABLE_OBJECT_ENTITY_CLASS = mir.entity.StorableObjectEntity.class; + + + private static Map POPUP_EMPTYLINE = new HashMap(); + protected static final ObjectStore o_store = ObjectStore.getInstance(); + private static final int _millisPerHour = 60 * 60 * 1000; + private static final int _millisPerMinute = 60 * 1000; + + static { + // always same object saves a little space + POPUP_EMPTYLINE.put("key", ""); + POPUP_EMPTYLINE.put("value", "--"); + } + + protected LoggerWrapper logger; + protected MirPropertiesConfiguration configuration; + protected String theTable; + protected String theCoreTable = null; + protected String thePKeyName = "id"; + protected int thePKeyType; + protected int thePKeyIndex; + protected boolean evaluatedMetaData = false; + protected ArrayList metadataFields; + protected ArrayList metadataLabels; + protected ArrayList metadataNotNullFields; + protected int[] metadataTypes; + protected Class theEntityClass; + protected List popupCache = null; + protected boolean hasPopupCache = false; + protected Map hashCache = null; + protected boolean hasTimestamp = true; + private String database_driver; + private String database_url; + private int defaultLimit; + + TimeZone timezone; + SimpleDateFormat internalDateFormat; + SimpleDateFormat userInputDateFormat; +/* + private SimpleDateFormat _dateFormatterOut; + private SimpleDateFormat _dateFormatterIn; + _dateFormatterOut = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + _dateFormatterIn = new SimpleDateFormat("yyyy-MM-dd HH:mm"); +*/ + + /** + * Kontruktor bekommt den Filenamen des Konfigurationsfiles ?bergeben. + * Aus diesem file werden Database.Logfile, + * Database.Username,Database.Password, + * Database.Host und Database.Adaptor + * ausgelesen und ein Broker f?r die Verbindugen zur Datenbank + * erzeugt. + * + * @param String confFilename Dateiname der Konfigurationsdatei + */ + public Database() throws StorageObjectFailure { + try { + configuration = MirPropertiesConfiguration.instance(); + } + catch (PropertiesConfigExc e) { + throw new StorageObjectFailure(e); + } + logger = new LoggerWrapper("Database"); + timezone = TimeZone.getTimeZone(configuration.getString("Mir.DefaultTimezone")); + internalDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + internalDateFormat.setTimeZone(timezone); + + userInputDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); + userInputDateFormat.setTimeZone(timezone); + + + String theAdaptorName = configuration.getString("Database.Adaptor"); + defaultLimit = Integer.parseInt(configuration.getString("Database.Limit")); + + try { + theEntityClass = GENERIC_ENTITY_CLASS; + } + catch (Throwable e) { + logger.error("Error in Database() constructor with " + theAdaptorName + " -- " + e.getMessage()); + throw new StorageObjectFailure("Error in Database() constructor.", e); + } + } + + /** + * Liefert die Entity-Klasse zur?ck, in der eine Datenbankzeile gewrappt + * wird. Wird die Entity-Klasse durch die erbende Klasse nicht ?berschrieben, + * wird eine mir.entity.GenericEntity erzeugt. + * + * @return Class-Objekt der Entity + */ + public java.lang.Class getEntityClass() { + return theEntityClass; + } + + /** + * Liefert die Standardbeschr?nkung von select-Statements zur?ck, also + * wieviel Datens?tze per Default selektiert werden. + * + * @return Standard-Anzahl der Datens?tze + */ + public int getLimit() { + return defaultLimit; + } + + /** + * Liefert den Namen des Primary-Keys zur?ck. Wird die Variable nicht von + * der erbenden Klasse ?berschrieben, so ist der Wert PKEY + * @return Name des Primary-Keys + */ + public String getIdName() { + return thePKeyName; + } + + /** + * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht. + * + * @return Name der Tabelle + */ + public String getTableName() { + return theTable; + } + + /* + * Dient dazu vererbte Tabellen bei objectrelationalen DBMS + * zu speichern, wenn die id einer Tabelle in der parenttabelle verwaltet + * wird. + * @return liefert theCoreTabel als String zurueck, wenn gesetzt, sonst + * the Table + */ + public String getCoreTable() { + if (theCoreTable != null) { + return theCoreTable; + } + else { + return theTable; + } + } + + /** + * Liefert Feldtypen der Felder der Tabelle zurueck (s.a. java.sql.Types) + * @return int-Array mit den Typen der Felder + * @exception StorageObjectException + */ + public int[] getTypes() throws StorageObjectFailure { + if (metadataTypes == null) { + get_meta_data(); + } + + return metadataTypes; + } + + /** + * Liefert eine Liste der Labels der Tabellenfelder + * @return ArrayListe mit Labeln + * @exception StorageObjectException + */ + public List getLabels() throws StorageObjectFailure { + if (metadataLabels == null) { + get_meta_data(); + } + + return metadataLabels; + } + + /** + * Liefert eine Liste der Felder der Tabelle + * @return ArrayList mit Feldern + * @exception StorageObjectException + */ + public List getFields() throws StorageObjectFailure { + if (metadataFields == null) { + get_meta_data(); + } + + return metadataFields; + } + + /* + * Gets value out of ResultSet according to type and converts to String + * @param inValue Wert aus ResultSet. + * @param aType Datenbanktyp. + * @return liefert den Wert als String zurueck. Wenn keine Umwandlung moeglich + * dann /unsupported value/ + */ + private String getValueAsString(ResultSet rs, int valueIndex, int aType) + throws StorageObjectFailure { + String outValue = null; + + if (rs != null) { + try { + switch (aType) { + case java.sql.Types.BIT: + outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0"; + + break; + + case java.sql.Types.INTEGER: + case java.sql.Types.SMALLINT: + case java.sql.Types.TINYINT: + case java.sql.Types.BIGINT: + + int out = rs.getInt(valueIndex); + + if (!rs.wasNull()) { + outValue = new Integer(out).toString(); + } + + break; + + case java.sql.Types.NUMERIC: + + /** @todo Numeric can be float or double depending upon + * metadata.getScale() / especially with oracle */ + long outl = rs.getLong(valueIndex); + + if (!rs.wasNull()) { + outValue = new Long(outl).toString(); + } + + break; + + case java.sql.Types.REAL: + + float tempf = rs.getFloat(valueIndex); + + if (!rs.wasNull()) { + tempf *= 10; + tempf += 0.5; + + int tempf_int = (int) tempf; + tempf = (float) tempf_int; + tempf /= 10; + outValue = "" + tempf; + outValue = outValue.replace('.', ','); + } + + break; + + case java.sql.Types.DOUBLE: + + double tempd = rs.getDouble(valueIndex); + + if (!rs.wasNull()) { + tempd *= 10; + tempd += 0.5; + + int tempd_int = (int) tempd; + tempd = (double) tempd_int; + tempd /= 10; + outValue = "" + tempd; + outValue = outValue.replace('.', ','); + } + + break; + + case java.sql.Types.CHAR: + case java.sql.Types.VARCHAR: + case java.sql.Types.LONGVARCHAR: + outValue = rs.getString(valueIndex); + + break; + + case java.sql.Types.LONGVARBINARY: + outValue = rs.getString(valueIndex); + + break; + + case java.sql.Types.TIMESTAMP: + + // it's important to use Timestamp here as getting it + // as a string is undefined and is only there for debugging + // according to the API. we can make it a string through formatting. + // -mh + Timestamp timestamp = (rs.getTimestamp(valueIndex)); + + if (!rs.wasNull()) { + java.util.Date date = new java.util.Date(timestamp.getTime()); + + Calendar calendar = new GregorianCalendar(); + calendar.setTime(date); + calendar.setTimeZone(timezone); + outValue = internalDateFormat.format(date); + + int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET); + String tzOffset = StringUtil.zeroPaddingNumber(Math.abs(offset) / _millisPerHour, 2, 2); + + if (offset<0) + outValue = outValue + "-"; + else + outValue = outValue + "+"; + outValue = outValue + tzOffset; + } + + break; + + default: + outValue = ""; + logger.warn("Unsupported Datatype: at " + valueIndex + " (" + aType + ")"); + } + } catch (SQLException e) { + throw new StorageObjectFailure("Could not get Value out of Resultset -- ", + e); + } + } + + return outValue; + } + + /* + * select-Operator um einen Datensatz zu bekommen. + * @param id Primaerschluessel des Datensatzes. + * @return liefert EntityObject des gefundenen Datensatzes oder null. + */ + public Entity selectById(String id) throws StorageObjectExc { + if ((id == null) || id.equals("")) { + throw new StorageObjectExc("Database.selectById: Missing id"); + } + + // ask object store for object + if (StoreUtil.implementsStorableObject(theEntityClass)) { + String uniqueId = id; + + if (theEntityClass.equals(StorableObjectEntity.class)) { + uniqueId += ("@" + theTable); + } + + StoreIdentifier search_sid = new StoreIdentifier(theEntityClass, uniqueId); + logger.debug("CACHE: (dbg) looking for sid " + search_sid.toString()); + + Entity hit = (Entity) o_store.use(search_sid); + + if (hit != null) { + return hit; + } + } + + Statement stmt = null; + Connection con = getPooledCon(); + Entity returnEntity = null; + + try { + ResultSet rs; + + /** @todo better prepared statement */ + String selectSql = + "select * from " + theTable + " where " + thePKeyName + "=" + id; + stmt = con.createStatement(); + rs = executeSql(stmt, selectSql); + + if (rs != null) { + if (evaluatedMetaData == false) { + evalMetaData(rs.getMetaData()); + } + + if (rs.next()) { + returnEntity = makeEntityFromResultSet(rs); + } + else { + logger.debug("No data for id: " + id + " in table " + theTable); + } + + rs.close(); + } + else { + logger.debug("No Data for Id " + id + " in Table " + theTable); + } + } + catch (SQLException sqe) { + throwSQLException(sqe, "selectById"); + return null; + } + catch (NumberFormatException e) { + logger.error("ID is no number: " + id); + } + finally { + freeConnection(con, stmt); + } + + return returnEntity; + } + + /** + * select-Operator um Datensaetze zu bekommen, die key = value erfuellen. + * @param key Datenbankfeld der Bedingung. + * @param value Wert die der key anehmen muss. + * @return EntityList mit den gematchten Entities + */ + public EntityList selectByFieldValue(String aField, String aValue) throws StorageObjectFailure { + return selectByFieldValue(aField, aValue, 0); + } + + /** + * select-Operator um Datensaetze zu bekommen, die key = value erfuellen. + * @param key Datenbankfeld der Bedingung. + * @param value Wert die der key anehmen muss. + * @param offset Gibt an ab welchem Datensatz angezeigt werden soll. + * @return EntityList mit den gematchten Entities + */ + public EntityList selectByFieldValue(String aField, String aValue, int offset) throws StorageObjectFailure { + return selectByWhereClause(aField + "=" + aValue, offset); + } + + /** + * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. + * Also offset wird der erste Datensatz genommen. + * + * @param wc where-Clause + * @return EntityList mit den gematchten Entities + * @exception StorageObjectException + */ + public EntityList selectByWhereClause(String where) throws StorageObjectFailure { + return selectByWhereClause(where, 0); + } + + /** + * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. + * Als maximale Anzahl wird das Limit auf der Konfiguration genommen. + * + * @param wc where-Clause + * @param offset ab welchem Datensatz. + * @return EntityList mit den gematchten Entities + * @exception StorageObjectException + */ + public EntityList selectByWhereClause(String whereClause, int offset) throws StorageObjectFailure { + return selectByWhereClause(whereClause, null, offset); + } + + /** + * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. + * Also offset wird der erste Datensatz genommen. + * Als maximale Anzahl wird das Limit auf der Konfiguration genommen. + * + * @param wc where-Clause + * @param ob orderBy-Clause + * @return EntityList mit den gematchten Entities + * @exception StorageObjectException + */ + public EntityList selectByWhereClause(String where, String order) throws StorageObjectFailure { + return selectByWhereClause(where, order, 0); + } + + /** + * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. + * Als maximale Anzahl wird das Limit auf der Konfiguration genommen. + * + * @param wc where-Clause + * @param ob orderBy-Clause + * @param offset ab welchem Datensatz + * @return EntityList mit den gematchten Entities + * @exception StorageObjectException + */ + public EntityList selectByWhereClause(String whereClause, String orderBy, int offset) throws StorageObjectFailure { + return selectByWhereClause(whereClause, orderBy, offset, defaultLimit); + } + + /** + * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck. + * @param aWhereClause where-Clause + * @param anOrderByClause orderBy-Clause + * @param offset ab welchem Datensatz + * @param limit wieviele Datens?tze + * @return EntityList mit den gematchten Entities + * @exception StorageObjectException + */ + public EntityList selectByWhereClause(String aWhereClause, String anOrderByClause, + int offset, int limit) throws StorageObjectFailure { + + // check o_store for entitylist + if (StoreUtil.implementsStorableObject(theEntityClass)) { + StoreIdentifier search_sid = + new StoreIdentifier( + theEntityClass, StoreContainerType.STOC_TYPE_ENTITYLIST, + StoreUtil.getEntityListUniqueIdentifierFor(theTable, aWhereClause, anOrderByClause, offset, limit)); + EntityList hit = (EntityList) o_store.use(search_sid); + + if (hit != null) { + logger.debug("CACHE (hit): " + search_sid.toString()); + + return hit; + } + } + + // local + EntityList theReturnList = null; + Connection con = null; + Statement stmt = null; + ResultSet rs; + int offsetCount = 0; + int count = 0; + + // build sql-statement + + /** @todo count sql string should only be assembled if we really count + * see below at the end of method //rk */ + if ((aWhereClause != null) && (aWhereClause.trim().length() == 0)) { + aWhereClause = null; + } + + StringBuffer countSql = + new StringBuffer("select count(*) from ").append(theTable); + StringBuffer selectSql = + new StringBuffer("select * from ").append(theTable); + + if (aWhereClause != null) { + selectSql.append(" where ").append(aWhereClause); + countSql.append(" where ").append(aWhereClause); + } + + if ((anOrderByClause != null) && !(anOrderByClause.trim().length() == 0)) { + selectSql.append(" order by ").append(anOrderByClause); + } + + if ((limit > -1) && (offset > -1)) { + selectSql.append(" LIMIT ").append(limit).append(" OFFSET ").append(offset); + } + + // execute sql + try { + con = getPooledCon(); + stmt = con.createStatement(); + + // selecting... + rs = executeSql(stmt, selectSql.toString()); + + if (rs != null) { + if (!evaluatedMetaData) { + evalMetaData(rs.getMetaData()); + } + + theReturnList = new EntityList(); + + Entity theResultEntity; + + while (rs.next()) { + theResultEntity = makeEntityFromResultSet(rs); + theReturnList.add(theResultEntity); + offsetCount++; + } + + rs.close(); + } + + // making entitylist infos + count = offsetCount; + + if (theReturnList != null) { + // now we decide if we have to know an overall count... + count = offsetCount; + + if ((limit > -1) && (offset > -1)) { + if (offsetCount == limit) { + /** @todo counting should be deffered to entitylist + * getSize() should be used */ + rs = executeSql(stmt, countSql.toString()); + + if (rs != null) { + if (rs.next()) { + count = rs.getInt(1); + } + + rs.close(); + } + else { + logger.error("Could not count: " + countSql); + } + } + } + + theReturnList.setCount(count); + theReturnList.setOffset(offset); + theReturnList.setWhere(aWhereClause); + theReturnList.setOrder(anOrderByClause); + theReturnList.setStorage(this); + theReturnList.setLimit(limit); + + if (offset >= limit) { + theReturnList.setPrevBatch(offset - limit); + } + + if ((offset + offsetCount) < count) { + theReturnList.setNextBatch(offset + limit); + } + + if (StoreUtil.implementsStorableObject(theEntityClass)) { + StoreIdentifier sid = theReturnList.getStoreIdentifier(); + logger.debug("CACHE (add): " + sid.toString()); + o_store.add(sid); + } + } + } + catch (SQLException sqe) { + throwSQLException(sqe, "selectByWhereClause"); + } + finally { + try { + if (con != null) { + freeConnection(con, stmt); + } + } catch (Throwable t) { + } + } + + return theReturnList; + } + + /** + * Bastelt aus einer Zeile der Datenbank ein EntityObjekt. + * + * @param rs Das ResultSetObjekt. + * @return Entity Die Entity. + */ + private Entity makeEntityFromResultSet(ResultSet rs) + throws StorageObjectFailure { + /** @todo OS: get Pkey from ResultSet and consult ObjectStore */ + Map theResultHash = new HashMap(); + String theResult = null; + int theType; + Entity returnEntity = null; + + try { + int size = metadataFields.size(); + + for (int i = 0; i < size; i++) { + // alle durchlaufen bis nix mehr da + theType = metadataTypes[i]; + + if (theType == java.sql.Types.LONGVARBINARY) { + InputStreamReader is = + (InputStreamReader) rs.getCharacterStream(i + 1); + + if (is != null) { + char[] data = new char[32768]; + StringBuffer theResultString = new StringBuffer(); + int len; + + while ((len = is.read(data)) > 0) { + theResultString.append(data, 0, len); + } + + is.close(); + theResult = theResultString.toString(); + } else { + theResult = null; + } + } else { + theResult = getValueAsString(rs, (i + 1), theType); + } + + if (theResult != null) { + theResultHash.put(metadataFields.get(i), theResult); + } + } + + if (theEntityClass != null) { + returnEntity = (Entity) theEntityClass.newInstance(); + returnEntity.setStorage(this); + returnEntity.setValues(theResultHash); + + if (returnEntity instanceof StorableObject) { + logger.debug("CACHE: ( in) " + returnEntity.getId() + " :" + theTable); + o_store.add(((StorableObject) returnEntity).getStoreIdentifier()); + } + } else { + throwStorageObjectException("Internal Error: theEntityClass not set!"); + } + } + catch (IllegalAccessException e) { + throwStorageObjectException("No access! -- " + e.getMessage()); + } + catch (IOException e) { + throwStorageObjectException("IOException! -- " + e.getMessage()); + } + catch (InstantiationException e) { + throwStorageObjectException("No Instatiation! -- " + e.getMessage()); + } + catch (SQLException sqe) { + throwSQLException(sqe, "makeEntityFromResultSet"); + + return null; + } + + return returnEntity; + } + + /** + * Inserts an entity into the database. + * + * @param theEntity + * @return der Wert des Primary-keys der eingef?gten Entity + */ + public String insert(Entity theEntity) throws StorageObjectFailure { + //cache + invalidatePopupCache(); + + // invalidating all EntityLists corresponding with theEntityClass + if (StoreUtil.implementsStorableObject(theEntityClass)) { + StoreContainerType stoc_type = + StoreContainerType.valueOf(theEntityClass, + StoreContainerType.STOC_TYPE_ENTITYLIST); + o_store.invalidate(stoc_type); + } + + String returnId = null; + Connection con = null; + PreparedStatement pstmt = null; + + try { + List streamedInput = theEntity.streamedInput(); + StringBuffer f = new StringBuffer(); + StringBuffer v = new StringBuffer(); + String aField; + String aValue; + boolean firstField = true; + + // make sql-string + for (int i = 0; i < getFields().size(); i++) { + aField = (String) getFields().get(i); + + if (!aField.equals(thePKeyName)) { + aValue = null; + + // exceptions + if (!theEntity.hasValueForField(aField) && ( + aField.equals("webdb_create") || + aField.equals("webdb_lastchange"))) { + aValue = "NOW()"; + } + else { + if ((streamedInput != null) && streamedInput.contains(aField)) { + aValue = "?"; + } + else { + if (theEntity.hasValueForField(aField)) { + aValue = + "'" + + JDBCStringRoutines.escapeStringLiteral((String) theEntity.getValue(aField)) + "'"; + } + } + } + + // wenn Wert gegeben, dann einbauen + if (aValue != null) { + if (firstField == false) { + f.append(","); + v.append(","); + } + else { + firstField = false; + } + + f.append(aField); + v.append(aValue); + } + } + } + // end for + + // insert into db + StringBuffer sqlBuf = + new StringBuffer("insert into ").append(theTable).append("(").append(f) + .append(") values (").append(v).append(")"); + String sql = sqlBuf.toString(); + + logger.debug("INSERT: " + sql); + con = getPooledCon(); + con.setAutoCommit(false); + pstmt = con.prepareStatement(sql); + + if (streamedInput != null) { + for (int i = 0; i < streamedInput.size(); i++) { + String inputString = + (String) theEntity.getValue((String) streamedInput.get(i)); + pstmt.setBytes(i + 1, inputString.getBytes()); + } + } + + int ret = pstmt.executeUpdate(); + + if (ret == 0) { + //insert failed + return null; + } + + pstmt = con.prepareStatement("select currval('" + getCoreTable() + "_id_seq')"); + + ResultSet rs = pstmt.executeQuery(); + rs.next(); + returnId = rs.getString(1); + theEntity.setId(returnId); + } + catch (SQLException sqe) { + throwSQLException(sqe, "insert"); + } + finally { + try { + con.setAutoCommit(true); + } + catch (Exception e) { + } + + freeConnection(con, pstmt); + } + + /** @todo store entity in o_store */ + return returnId; + } + + /** + * Updates an entity in the database + * + * @param theEntity + */ + public void update(Entity theEntity) throws StorageObjectFailure { + Connection con = null; + PreparedStatement pstmt = null; + + /** @todo this is stupid: why do we prepare statement, when we + * throw it away afterwards. should be regular statement + * update/insert could better be one routine called save() + * that chooses to either insert or update depending if we + * have a primary key in the entity. i don't know if we + * still need the streamed input fields. // rk */ + /** @todo extension: check if Entity did change, otherwise we don't need + * the roundtrip to the database */ + /** invalidating corresponding entitylists in o_store*/ + if (StoreUtil.implementsStorableObject(theEntityClass)) { + StoreContainerType stoc_type = + StoreContainerType.valueOf(theEntityClass, + StoreContainerType.STOC_TYPE_ENTITYLIST); + o_store.invalidate(stoc_type); + } + + List streamedInput = theEntity.streamedInput(); + String id = theEntity.getId(); + String aField; + StringBuffer fv = new StringBuffer(); + boolean firstField = true; + + //cache + invalidatePopupCache(); + + // build sql statement + for (int i = 0; i < getFields().size(); i++) { + aField = (String) metadataFields.get(i); + + // only normal cases + if ( !(aField.equals(thePKeyName) || + aField.equals("webdb_create") || + aField.equals("webdb_lastchange") || + ((streamedInput != null) && streamedInput.contains(aField)))) { + if (theEntity.hasValueForField(aField)) { + if (firstField == false) { + fv.append(", "); + } + else { + firstField = false; + } + + fv.append(aField).append("='").append(JDBCStringRoutines.escapeStringLiteral((String) theEntity.getValue(aField))).append("'"); + + // fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'"); + } + } + } + + StringBuffer sql = + new StringBuffer("update ").append(theTable).append(" set ").append(fv); + + // exceptions + if (metadataFields.contains("webdb_lastchange")) { + sql.append(",webdb_lastchange=NOW()"); + } + + // special case: the webdb_create requires the field in yyyy-mm-dd HH:mm + // format so anything extra will be ignored. -mh + if (metadataFields.contains("webdb_create") && + theEntity.hasValueForField("webdb_create")) { + // minimum of 10 (yyyy-mm-dd)... + if (theEntity.getValue("webdb_create").length() >= 10) { + String dateString = theEntity.getValue("webdb_create"); + + // if only 10, then add 00:00 so it doesn't throw a ParseException + if (dateString.length() == 10) { + dateString = dateString + " 00:00"; + } + + // TimeStamp stuff + try { + java.util.Date d = userInputDateFormat.parse(dateString); +// Timestamp tStamp = new Timestamp(d.getTime()); + sql.append(",webdb_create='" + JDBCStringRoutines.formatDate(d) + "'"); + } + catch (ParseException e) { + throw new StorageObjectFailure(e); + } + } + } + + if (streamedInput != null) { + for (int i = 0; i < streamedInput.size(); i++) { + sql.append(",").append(streamedInput.get(i)).append("=?"); + } + } + + sql.append(" where id=").append(id); + logger.debug("UPDATE: " + sql); + + try { + con = getPooledCon(); + con.setAutoCommit(false); + pstmt = con.prepareStatement(sql.toString()); + + if (streamedInput != null) { + for (int i = 0; i < streamedInput.size(); i++) { + String inputString = + theEntity.getValue((String) streamedInput.get(i)); + pstmt.setBytes(i + 1, inputString.getBytes()); + } + } + + pstmt.executeUpdate(); + } + catch (SQLException sqe) { + throwSQLException(sqe, "update"); + } + finally { + try { + con.setAutoCommit(true); + } + catch (Exception e) { + ; + } + + freeConnection(con, pstmt); + } + } + + /* + * delete-Operator + * @param id des zu loeschenden Datensatzes + * @return boolean liefert true zurueck, wenn loeschen erfolgreich war. + */ + public boolean delete(String id) throws StorageObjectFailure { + invalidatePopupCache(); + + // ostore send notification + if (StoreUtil.implementsStorableObject(theEntityClass)) { + String uniqueId = id; + + if (theEntityClass.equals(StorableObjectEntity.class)) { + uniqueId += ("@" + theTable); + } + + logger.debug("CACHE: (del) " + id); + + StoreIdentifier search_sid = + new StoreIdentifier(theEntityClass, + StoreContainerType.STOC_TYPE_ENTITY, uniqueId); + o_store.invalidate(search_sid); + } + + /** @todo could be prepared Statement */ + Statement stmt = null; + Connection con = null; + int res = 0; + String sql = + "delete from " + theTable + " where " + thePKeyName + "='" + id + "'"; + + //theLog.printInfo("DELETE " + sql); + try { + con = getPooledCon(); + stmt = con.createStatement(); + res = stmt.executeUpdate(sql); + } catch (SQLException sqe) { + throwSQLException(sqe, "delete"); + } finally { + freeConnection(con, stmt); + } + + return (res > 0) ? true : false; + } + + /** + * Deletes entities based on a where clause + * + * @param aWhereClause + * @return + * @throws StorageObjectFailure + */ + public int deleteByWhereClause(String aWhereClause) throws StorageObjectFailure { + invalidatePopupCache(); + if (StoreUtil.implementsStorableObject(theEntityClass)) { + StoreContainerType stoc_type = StoreContainerType.valueOf(theEntityClass, StoreContainerType.STOC_TYPE_ENTITYLIST); + o_store.invalidate(stoc_type); + } + + Statement stmt = null; + Connection con = null; + int res = 0; + String sql = + "delete from " + theTable + " where " + aWhereClause; + + //theLog.printInfo("DELETE " + sql); + try { + con = getPooledCon(); + stmt = con.createStatement(); + res = stmt.executeUpdate(sql); + } + catch (SQLException sqe) { + throwSQLException(sqe, "delete"); + } + finally { + freeConnection(con, stmt); + } + + return res; + } + + /* noch nicht implementiert. + * @return immer false + */ + public boolean delete(EntityList theEntityList) { + invalidatePopupCache(); + + return false; + } + + /* invalidates the popupCache + */ + protected void invalidatePopupCache() { + /** @todo invalidates toooo much */ + popupCache = null; + hashCache = null; + } + + /** + * Diese Methode fuehrt den Sqlstring sql aus und timed im Logfile. + * @param stmt Statemnt + * @param sql Sql-String + * @return ResultSet + * @exception StorageObjectException + */ + public ResultSet executeSql(Statement stmt, String sql) + throws StorageObjectFailure, SQLException { + ResultSet rs; + long startTime = System.currentTimeMillis(); + + try { + rs = stmt.executeQuery(sql); + + logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql); + } + catch (SQLException e) { + logger.error(e.getMessage() +"\n" + (System.currentTimeMillis() - startTime) + "ms. for: " + sql); + throw e; + } + + return rs; + } +/* + public ResultSet executeSql(String sql) throws StorageObjectFailure, SQLException { + long startTime = System.currentTimeMillis(); + Connection connection = null; + Statement statement = null; + + try { + connection = getPooledCon(); + statement = connection.createStatement(); + ResultSet result; + + result = statement.executeQuery(sql); + + logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql); + return result; + } + catch (Throwable e) { + logger.error(e.getMessage() +"\n" + (System.currentTimeMillis() - startTime) + "ms. for: " + sql); + throw new StorageObjectFailure(e); + } + finally { + if (connection!=null) { + freeConnection(connection, statement); + } + } + } +*/ + private Map processRow(ResultSet aResultSet) throws StorageObjectFailure, StorageObjectExc { + try { + Map result = new HashMap(); + ResultSetMetaData metaData = aResultSet.getMetaData(); + int nrColumns = metaData.getColumnCount(); + for (int i=0; i0) + return (Map) resultList.get(0); + else + return null; + } + finally { + } + } + catch (Throwable t) { + throw new StorageObjectFailure(t); + } + }; + + public String executeFreeSingleValueSql(String sql) throws StorageObjectFailure, StorageObjectExc { + Map row = executeFreeSingleRowSql(sql); + + if (row==null) + return null; + + Iterator i = row.values().iterator(); + if (i.hasNext()) + return (String) i.next(); + else + return null; + }; + + /** + * returns the number of rows in the table + */ + public int getSize(String where) throws SQLException, StorageObjectFailure { + long startTime = System.currentTimeMillis(); + String sql = "SELECT Count(*) FROM " + theTable; + + if ((where != null) && (where.length() != 0)) { + sql = sql + " where " + where; + } + + Connection con = null; + Statement stmt = null; + int result = 0; + + try { + con = getPooledCon(); + stmt = con.createStatement(); + + ResultSet rs = executeSql(stmt, sql); + + while (rs.next()) { + result = rs.getInt(1); + } + } + catch (SQLException e) { + logger.error("Database.getSize: " + e.getMessage()); + } + finally { + freeConnection(con, stmt); + } + + //theLog.printInfo(theTable + " has "+ result +" rows where " + where); + logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql); + + return result; + } + + public int executeUpdate(Statement stmt, String sql) + throws StorageObjectFailure, SQLException { + int rs; + long startTime = System.currentTimeMillis(); + + try { + rs = stmt.executeUpdate(sql); + + logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql); + } + catch (SQLException e) { + logger.error("Failed: " + (System.currentTimeMillis() - startTime) + "ms. for: " + sql); + throw e; + } + + return rs; + } + + public int executeUpdate(String sql) + throws StorageObjectFailure, SQLException { + int result = -1; + long startTime = System.currentTimeMillis(); + Connection con = null; + PreparedStatement pstmt = null; + + try { + con = getPooledCon(); + pstmt = con.prepareStatement(sql); + result = pstmt.executeUpdate(); + } + catch (Throwable e) { + logger.error("Database.executeUpdate(" + sql + "): " + e.getMessage()); + throw new StorageObjectFailure("Database.executeUpdate(" + sql + "): " + e.getMessage(), e); + } + finally { + freeConnection(con, pstmt); + } + + logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql); + return result; + } + + /** + * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend + * @param md ResultSetMetaData + * @exception StorageObjectException + */ + private void evalMetaData(ResultSetMetaData md) throws StorageObjectFailure { + this.evaluatedMetaData = true; + this.metadataFields = new ArrayList(); + this.metadataLabels = new ArrayList(); + this.metadataNotNullFields = new ArrayList(); + + try { + int numFields = md.getColumnCount(); + this.metadataTypes = new int[numFields]; + + String aField; + int aType; + + for (int i = 1; i <= numFields; i++) { + aField = md.getColumnName(i); + metadataFields.add(aField); + metadataLabels.add(md.getColumnLabel(i)); + aType = md.getColumnType(i); + metadataTypes[i - 1] = aType; + + if (aField.equals(thePKeyName)) { + thePKeyType = aType; + thePKeyIndex = i; + } + + if (md.isNullable(i) == ResultSetMetaData.columnNullable) { + metadataNotNullFields.add(aField); + } + } + } + catch (SQLException e) { + throwSQLException(e, "evalMetaData"); + } + } + + /** + * Wertet die Metadaten eines Resultsets fuer eine Tabelle aus, + * um die alle Columns und Typen einer Tabelle zu ermitteln. + */ + private void get_meta_data() throws StorageObjectFailure { + Connection con = null; + PreparedStatement pstmt = null; + String sql = "select * from " + theTable + " where 0=1"; + + try { + con = getPooledCon(); + pstmt = con.prepareStatement(sql); + + logger.debug("METADATA: " + sql); + ResultSet rs = pstmt.executeQuery(); + evalMetaData(rs.getMetaData()); + rs.close(); + } + catch (SQLException e) { + throwSQLException(e, "get_meta_data"); + } + finally { + freeConnection(con, pstmt); + } + } + + public Connection getPooledCon() throws StorageObjectFailure { + Connection con = null; + + try { + con = SQLManager.getInstance().requestConnection(); + } + catch (SQLException e) { + logger.error("could not connect to the database " + e.getMessage()); + + throw new StorageObjectFailure("Could not connect to the database", e); + } + + return con; + } + + public void freeConnection(Connection con, Statement stmt) + throws StorageObjectFailure { + SQLManager.closeStatement(stmt); + SQLManager.getInstance().returnConnection(con); + } + + /** + * Wertet SQLException aus und wirft dannach eine StorageObjectException + * @param sqe SQLException + * @param wo Funktonsname, in der die SQLException geworfen wurde + * @exception StorageObjectException + */ + protected void throwSQLException(SQLException sqe, String aFunction) throws StorageObjectFailure { + String state = ""; + String message = ""; + int vendor = 0; + + if (sqe != null) { + state = sqe.getSQLState(); + message = sqe.getMessage(); + vendor = sqe.getErrorCode(); + } + + String information = + "SQL Error: " + + "state= " + state + + ", vendor= " + vendor + + ", message=" + message + + ", function= " + aFunction; + + logger.error(information); + + throw new StorageObjectFailure(information, sqe); + } + + protected void _throwStorageObjectException(Exception e, String aFunction) + throws StorageObjectFailure { + + if (e != null) { + logger.error(e.getMessage() + aFunction); + throw new StorageObjectFailure(aFunction, e); + } + } + + /** + * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach + * eine StorageObjectException + * @param message Nachricht mit dem Fehler + * @exception StorageObjectException + */ + void throwStorageObjectException(String aMessage) throws StorageObjectFailure { + logger.error(aMessage); + throw new StorageObjectFailure(aMessage, null); + } +} diff --git a/source/mir/storage/StorageObject.java b/source/mir/storage/StorageObject.java index ac6cd29e..921ce85d 100755 --- a/source/mir/storage/StorageObject.java +++ b/source/mir/storage/StorageObject.java @@ -36,9 +36,6 @@ import java.sql.Statement; import java.util.List; import java.util.Map; -import freemarker.template.SimpleHash; -import freemarker.template.SimpleList; - import mir.entity.Entity; import mir.entity.EntityList; @@ -184,12 +181,6 @@ public interface StorageObject { /** * Dokumentation siehe Database.java - * @return SimpleHash - */ - abstract public SimpleHash getHashData(); - - /** - * Dokumentation siehe Database.java * @return Connection * @exception StorageObjectException */ @@ -238,25 +229,14 @@ public interface StorageObject { abstract public String executeFreeSingleValueSql(String sql) throws StorageObjectFailure, StorageObjectExc ; /** - * Dokumentation siehe Database.java * @param con * @param stmt */ - abstract public void freeConnection(Connection con, Statement stmt) - throws StorageObjectFailure; - - /** - * Dokumentation siehe Database.java - * @return - */ - abstract public SimpleList getPopupData() throws StorageObjectFailure; + abstract public void freeConnection(Connection con, Statement stmt) throws StorageObjectFailure; - abstract public int executeUpdate(Statement a, String sql) - throws StorageObjectFailure, SQLException; + abstract public int executeUpdate(Statement a, String sql) throws StorageObjectFailure, SQLException; - abstract public int executeUpdate(String sql) - throws StorageObjectFailure, SQLException; + abstract public int executeUpdate(String sql) throws StorageObjectFailure, SQLException; - abstract public int getSize(String where) - throws SQLException, StorageObjectFailure; + abstract public int getSize(String where) throws SQLException, StorageObjectFailure; } diff --git a/source/mir/util/DateTimeFunctions.java b/source/mir/util/DateTimeFunctions.java index 4bfe083b..691bd57a 100755 --- a/source/mir/util/DateTimeFunctions.java +++ b/source/mir/util/DateTimeFunctions.java @@ -36,13 +36,11 @@ import java.util.GregorianCalendar; import java.util.SimpleTimeZone; import java.util.TimeZone; -import mir.log.*; - public class DateTimeFunctions { /** * private parameter-less constructor to prevent construction */ - private static LoggerWrapper logger = new LoggerWrapper("Utility.DatTimeFunctions"); +// private static LoggerWrapper logger = new LoggerWrapper("Utility.DatTimeFunctions"); private DateTimeFunctions() { @@ -150,7 +148,7 @@ public class DateTimeFunctions { return calendar.getTime(); } catch (Throwable t) { - logger.error("DateTimeFunctions.parseW3CDTFString: error parsing " + aString + ": " + t.toString()); +// logger.error("DateTimeFunctions.parseW3CDTFString: error parsing " + aString + ": " + t.toString()); throw new UtilFailure(t); } diff --git a/source/mir/util/HTTPParsedRequest.java b/source/mir/util/HTTPParsedRequest.java index ba307968..3ca02f11 100755 --- a/source/mir/util/HTTPParsedRequest.java +++ b/source/mir/util/HTTPParsedRequest.java @@ -59,7 +59,7 @@ public class HTTPParsedRequest { private LoggerWrapper logger; public HTTPParsedRequest(HttpServletRequest aRequest, String anEncoding, int aMaxUploadSize, String aTempDir) throws UtilExc, UtilFailure { - logger = new LoggerWrapper("Utility,HTTPParsedRequest"); + logger = new LoggerWrapper("Utility.HTTPParsedRequest"); request = aRequest; encoding = anEncoding; diff --git a/source/mir/util/PropertiesManipulator.java b/source/mir/util/PropertiesManipulator.java index ae88073e..c76cbbd6 100755 --- a/source/mir/util/PropertiesManipulator.java +++ b/source/mir/util/PropertiesManipulator.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.util; @@ -202,7 +202,6 @@ public class PropertiesManipulator { private final static String SEPARATOR = "[\t\n\r ]*[:=]?[\t\n\r ]*"; private final static String VALUE = "(([\\\\].)|([^\\\\]))*"; - public static PropertiesManipulator readProperties(InputStream anInputStream) throws PropertiesManipulatorExc, PropertiesManipulatorFailure { return readProperties(anInputStream, "ISO-8859-1"); } diff --git a/source/mircoders/entity/EntityContent.java b/source/mircoders/entity/EntityContent.java index 4c76c9e9..8f5a4ee6 100755 --- a/source/mircoders/entity/EntityContent.java +++ b/source/mircoders/entity/EntityContent.java @@ -45,15 +45,12 @@ import mir.storage.StorageObjectFailure; import mircoders.storage.DatabaseContent; import mircoders.storage.DatabaseContentToMedia; import mircoders.storage.DatabaseContentToTopics; -import freemarker.template.SimpleScalar; -import freemarker.template.TemplateModel; -import freemarker.template.TemplateModelException; /** * this class implements mapping of one line of the database table content * to a java object * - * @version $Id: EntityContent.java,v 1.19.2.1 2003/06/19 02:24:12 zapata Exp $ + * @version $Id: EntityContent.java,v 1.19.2.2 2003/09/03 17:49:39 zapata Exp $ * @author mir-coders group * */ @@ -164,87 +161,6 @@ public class EntityContent extends Entity } /** - * overridden method getValue to include formatted date into every - * entityContent - */ - - public TemplateModel get(java.lang.String key) throws TemplateModelException - { - if (key!=null) { - if (_entCache.containsKey(key)) { - return (TemplateModel)_entCache.get(key); - } -/* if (key.equals("to_comments")) { - try { - _entCache.put(key, getComments()); - return (TemplateModel)_entCache.get(key); - } - catch (Exception ex) { - logger.warn("EntityContent.getComments: could not fetch data " + ex.toString()); - - throw new TemplateModelException(ex.toString()); - } - } - if (key.equals("to_media_images")) { - try { - _entCache.put(key, getImagesForContent()); - return (TemplateModel)_entCache.get(key); - } - catch (Exception ex) { - logger.warn("EntityContent.getImagesForContent: could not fetch data " + ex.toString()); - throw new TemplateModelException(ex.toString()); - } - } - if (key.equals("to_media_audio")) { - try { - _entCache.put(key, getAudioForContent()); - return (TemplateModel)_entCache.get(key); - } - catch (Exception ex) { - logger.warn("EntityContent.getAudioForContent: could not fetch data " + ex.toString()); - throw new TemplateModelException(ex.toString()); - } - } - if (key.equals("to_media_video")) { - try { - _entCache.put(key, getVideoForContent()); - return (TemplateModel)_entCache.get(key); - } - catch (Exception ex) { - logger.warn("EntityContent.getVideoForContent: could not fetch data " + ex.toString()); - throw new TemplateModelException(ex.toString()); - } - } - if (key.equals("to_media_other")) { - try { - _entCache.put(key, getOtherMediaForContent()); - return (TemplateModel)_entCache.get(key); - } - catch (Exception ex) { - logger.warn("EntityContent.getOtherMediaForContent: could not fetch data " + ex.toString()); - throw new TemplateModelException(ex.toString()); - } - } - else if (key.equals("to_topics")) { - try { - _entCache.put(key, - DatabaseContentToTopics.getInstance().getTopics(this)); - return (TemplateModel)_entCache.get(key); - } - catch (Exception ex) { - logger.warn("EntityContent.getTopics: could not fetch data " + ex.toString()); - throw new TemplateModelException(ex.toString()); - } - } - else { - return new SimpleScalar(getValue(key)); - } -*/ - } - return null; - } - - /** * overridden method setValues to patch creator_main_url */ public void setValues(Map theStringValues) { @@ -261,15 +177,6 @@ public class EntityContent extends Entity super.setValues(theStringValues); } - /** - * fetches all the comments belonging to an article - * - * @return freemarker.template.SimpleList - */ -// private EntityList getComments() throws StorageObjectFailure { -// return ((DatabaseContent)theStorageObject).getComments(this); -// } - private boolean hasMedia() throws StorageObjectFailure { if (_hasMedia == null) { @@ -282,43 +189,4 @@ public class EntityContent extends Entity } return _hasMedia.booleanValue(); } - - //######## @todo all of the following getBlahForContent should have - // and optimized version where LIMIT=1 sql for list view. - private EntityList getImagesForContent() - throws StorageObjectFailure, TemplateModelException - { - if (hasMedia()) - return DatabaseContentToMedia.getInstance().getImages(this); - else - return null; - } - - private EntityList getAudioForContent() - throws StorageObjectFailure, TemplateModelException - { - if (hasMedia()) - return DatabaseContentToMedia.getInstance().getAudio(this) ; - else - return null; - } - - private EntityList getVideoForContent() - throws StorageObjectFailure, TemplateModelException - { - if (hasMedia()) - return DatabaseContentToMedia.getInstance().getVideo(this) ; - else - return null; - } - - private EntityList getOtherMediaForContent() - throws StorageObjectFailure, TemplateModelException - { - if (hasMedia()) - return DatabaseContentToMedia.getInstance().getOther(this); - else - return null; - } - } diff --git a/source/mircoders/entity/EntityMedia.java b/source/mircoders/entity/EntityMedia.java deleted file mode 100755 index 029793a9..00000000 --- a/source/mircoders/entity/EntityMedia.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with any library licensed under the Apache Software License, - * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library - * (or with modified versions of the above that use the same license as the above), - * and distribute linked combinations including the two. You must obey the - * GNU General Public License in all respects for all of the code used other than - * the above mentioned libraries. If you modify this file, you may extend this - * exception to your version of the file, but you are not obligated to do so. - * If you do not wish to do so, delete this exception statement from your version. - */ -package mircoders.entity; - -import mir.entity.Entity; -import mir.storage.StorageObject; -import mir.storage.StorageObjectExc; -import mir.storage.StorageObjectFailure; -import mircoders.storage.DatabaseMedia; -/** - * Diese Klasse enth?lt die Daten eines MetaObjekts - * - * @author RK - * @version 29.6.1999 - */ - - -public class EntityMedia extends Entity -{ - - public EntityMedia(){ - super(); - } - - public EntityMedia(StorageObject theStorage) - { - this(); - setStorage(theStorage); - } - - /** - * fetches the MediaType entry assiciated w/ this media - * - * @return mir.entity.Entity - */ - public Entity getMediaType() throws StorageObjectFailure { - try { - return ( (DatabaseMedia) theStorageObject).getMediaType(this); - } - catch (StorageObjectFailure e) { - throw new StorageObjectFailure("getMediaType(): ", e); - } - catch (StorageObjectExc e) { - throw new StorageObjectFailure("getMediaType(): ", e); - } - - } -} diff --git a/source/mircoders/entity/EntityUploadedMedia.java b/source/mircoders/entity/EntityUploadedMedia.java index 2d5e0115..d48ed408 100755 --- a/source/mircoders/entity/EntityUploadedMedia.java +++ b/source/mircoders/entity/EntityUploadedMedia.java @@ -1,215 +1,206 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with any library licensed under the Apache Software License, - * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library - * (or with modified versions of the above that use the same license as the above), - * and distribute linked combinations including the two. You must obey the - * GNU General Public License in all respects for all of the code used other than - * the above mentioned libraries. If you modify this file, you may extend this - * exception to your version of the file, but you are not obligated to do so. - * If you do not wish to do so, delete this exception statement from your version. - */ -package mircoders.entity; - -import java.sql.SQLException; -import java.util.Map; - -import mir.entity.Entity; -import mir.log.LoggerWrapper; -import mir.media.MediaHelper; -import mir.media.MirMedia; -import mir.misc.NumberUtils; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import mircoders.storage.DatabaseUploadedMedia; -import freemarker.template.SimpleList; -import freemarker.template.SimpleScalar; -import freemarker.template.TemplateModel; -import freemarker.template.TemplateModelException; - -/** - * - * @author mh, mir-coders group - * @version $Id: EntityUploadedMedia.java,v 1.26 2003/04/21 12:42:53 idfx Exp $ - */ - - -public class EntityUploadedMedia extends Entity { - - - public EntityUploadedMedia() { - super(); - - logger = new LoggerWrapper("Entity.UploadedMedia"); - } - - public EntityUploadedMedia(StorageObject theStorage) { - this(); - setStorage(theStorage); - } - - public void update() throws StorageObjectFailure { - super.update(); - try { - theStorageObject.executeUpdate("update content set is_produced='0' where exists(select * from content_x_media where to_content=content.id and to_media=" + getId()+")"); - } - catch (SQLException e) { - throwStorageObjectFailure(e, "EntityAudio :: update :: failed!! "); - } - } - - public void setValues(Map theStringValues) { - if (theStringValues != null) { - if (!theStringValues.containsKey("is_published")) - theStringValues.put("is_published", "0"); - } - super.setValues(theStringValues); - } - - - /** - * fetches the MediaType entry assiciated w/ this media - * - * @return mir.entity.Entity - */ - public Entity getMediaType() throws StorageObjectFailure { - Entity ent = null; - try { - ent = DatabaseUploadedMedia.getInstance().getMediaType(this); - } - catch (StorageObjectFailure e) { - throwStorageObjectFailure(e, "get MediaType failed -- "); - } - return ent; - } - - public String getValue(String key) { - String returnValue = null; - - if (key != null) { - if (key.equals("big_icon")) - returnValue = getBigIconName(); - else if (key.equals("descr") || key.equals("media_descr")) - returnValue = getDescr(); - else if (key.equals("mediatype")) - returnValue = getMediaTypeString(); - else if (key.equals("mimetype")) - returnValue = getMimeType(); - else if (key.equals("human_readable_size")) { - String size = super.getValue("size"); - if (size != null) - returnValue = NumberUtils.humanReadableSize(Double.parseDouble(size)); - } - else - returnValue = super.getValue(key); - } - return returnValue; - } - - public TemplateModel get(java.lang.String key) throws TemplateModelException { - if (key.equals("url")) - return getUrl(); - return new SimpleScalar(getValue(key)); - } - - // @todo all these methods should be merged into 1 - // and the MediaHandler should be cached somehow. - private String getMediaTypeString() { - MirMedia mediaHandler = null; - Entity mediaType = null; - - try { - mediaType = getMediaType(); - mediaHandler = MediaHelper.getHandler(mediaType); - String t; - if (mediaHandler.isAudio()) - return "audio"; - else if (mediaHandler.isImage()) - return "image"; - else if (mediaHandler.isVideo()) - return "video"; - else - return "other"; - } - catch (Exception ex) { - logger.warn("EntityUploadedMedia.getMediaTypeString: could not fetch data: " + ex.toString()); - } - return null; - } - - private String getBigIconName() { - MirMedia mediaHandler = null; - Entity mediaType = null; - - try { - mediaType = getMediaType(); - mediaHandler = MediaHelper.getHandler(mediaType); - return mediaHandler.getBigIconName(); - } - catch (Exception ex) { - logger.warn("EntityUploadedMedia.getBigIconName: could not fetch data: " + ex.toString()); - } - return null; - } - - private SimpleList getUrl() { - MirMedia mediaHandler = null; - Entity mediaType = null; - - try { - mediaType = getMediaType(); - mediaHandler = MediaHelper.getHandler(mediaType); - return mediaHandler.getURL(this, mediaType); - } - catch (Throwable t) { - logger.warn("EntityUploadedMedia.getUrl: could not fetch data: " + t.toString()); - } - return null; - } - - private String getDescr() { - MirMedia mediaHandler = null; - Entity mediaType = null; - - try { - mediaType = getMediaType(); - mediaHandler = MediaHelper.getHandler(mediaType); - return mediaHandler.getDescr(mediaType); - } - catch (Exception ex) { - logger.warn("EntityUploadedMedia.getDescr: could not fetch data: " + ex.toString()); - } - return null; - } - private String getMimeType() { - Entity mediaType = null; - - try { - mediaType = getMediaType(); - return mediaType.getValue("mime_type"); - } - catch (Exception ex) { - logger.warn("EntityUploadedMedia.getBigIconName: could not fetch data: " + ex.toString()); - } - 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 mircoders.entity; + +import java.sql.SQLException; +import java.util.List; +import java.util.Map; + +import mir.entity.Entity; +import mir.log.LoggerWrapper; +import mir.media.MediaHelper; +import mir.media.MirMedia; +import mir.misc.NumberUtils; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; +import mircoders.storage.DatabaseUploadedMedia; + +/** + * + * @author mh, mir-coders group + * @version $Id: EntityUploadedMedia.java,v 1.26.2.1 2003/09/03 17:49:39 zapata Exp $ + */ + + +public class EntityUploadedMedia extends Entity { + + + public EntityUploadedMedia() { + super(); + + logger = new LoggerWrapper("Entity.UploadedMedia"); + } + + public EntityUploadedMedia(StorageObject theStorage) { + this(); + setStorage(theStorage); + } + + public void update() throws StorageObjectFailure { + super.update(); + try { + theStorageObject.executeUpdate("update content set is_produced='0' where exists(select * from content_x_media where to_content=content.id and to_media=" + getId()+")"); + } + catch (SQLException e) { + throwStorageObjectFailure(e, "EntityAudio :: update :: failed!! "); + } + } + + public void setValues(Map theStringValues) { + if (theStringValues != null) { + if (!theStringValues.containsKey("is_published")) + theStringValues.put("is_published", "0"); + } + super.setValues(theStringValues); + } + + + /** + * fetches the MediaType entry assiciated w/ this media + * + * @return mir.entity.Entity + */ + public Entity getMediaType() throws StorageObjectFailure { + Entity ent = null; + try { + ent = DatabaseUploadedMedia.getInstance().getMediaType(this); + } + catch (StorageObjectFailure e) { + throwStorageObjectFailure(e, "get MediaType failed -- "); + } + return ent; + } + + public String getValue(String key) { + String returnValue = null; + + if (key != null) { + if (key.equals("big_icon")) + returnValue = getBigIconName(); + else if (key.equals("descr") || key.equals("media_descr")) + returnValue = getDescr(); + else if (key.equals("mediatype")) + returnValue = getMediaTypeString(); + else if (key.equals("mimetype")) + returnValue = getMimeType(); + else if (key.equals("human_readable_size")) { + String size = super.getValue("size"); + if (size != null) + returnValue = NumberUtils.humanReadableSize(Double.parseDouble(size)); + } + else + returnValue = super.getValue(key); + } + return returnValue; + } + + // @todo all these methods should be merged into 1 + // and the MediaHandler should be cached somehow. + private String getMediaTypeString() { + MirMedia mediaHandler = null; + Entity mediaType = null; + + try { + mediaType = getMediaType(); + mediaHandler = MediaHelper.getHandler(mediaType); + String t; + if (mediaHandler.isAudio()) + return "audio"; + else if (mediaHandler.isImage()) + return "image"; + else if (mediaHandler.isVideo()) + return "video"; + else + return "other"; + } + catch (Exception ex) { + logger.warn("EntityUploadedMedia.getMediaTypeString: could not fetch data: " + ex.toString()); + } + return null; + } + + private String getBigIconName() { + MirMedia mediaHandler = null; + Entity mediaType = null; + + try { + mediaType = getMediaType(); + mediaHandler = MediaHelper.getHandler(mediaType); + return mediaHandler.getBigIconName(); + } + catch (Exception ex) { + logger.warn("EntityUploadedMedia.getBigIconName: could not fetch data: " + ex.toString()); + } + return null; + } + + private List getUrl() { + MirMedia mediaHandler = null; + Entity mediaType = null; + + try { + mediaType = getMediaType(); + mediaHandler = MediaHelper.getHandler(mediaType); + return mediaHandler.getURL(this, mediaType); + } + catch (Throwable t) { + logger.warn("EntityUploadedMedia.getUrl: could not fetch data: " + t.toString()); + } + return null; + } + + private String getDescr() { + MirMedia mediaHandler = null; + Entity mediaType = null; + + try { + mediaType = getMediaType(); + mediaHandler = MediaHelper.getHandler(mediaType); + return mediaHandler.getDescr(mediaType); + } + catch (Exception ex) { + logger.warn("EntityUploadedMedia.getDescr: could not fetch data: " + ex.toString()); + } + return null; + } + private String getMimeType() { + Entity mediaType = null; + + try { + mediaType = getMediaType(); + return mediaType.getValue("mime_type"); + } + catch (Exception ex) { + logger.warn("EntityUploadedMedia.getBigIconName: could not fetch data: " + ex.toString()); + } + return null; + } + +} diff --git a/source/mircoders/localizer/basic/MirBasicAdminInterfaceLocalizer.java b/source/mircoders/localizer/basic/MirBasicAdminInterfaceLocalizer.java index 7196ea11..4ed7d6a7 100755 --- a/source/mircoders/localizer/basic/MirBasicAdminInterfaceLocalizer.java +++ b/source/mircoders/localizer/basic/MirBasicAdminInterfaceLocalizer.java @@ -236,6 +236,33 @@ public class MirBasicAdminInterfaceLocalizer implements MirAdminInterfaceLocaliz } } + protected static class SetCommentFieldsOperation extends CommentModifyingOperation { + private Map values; + + public SetCommentFieldsOperation(String aName, String aFields[], String aValues[]) throws MirLocalizerExc { + super(aName); + + values = new HashMap(); + + for (int i=0; i0) - condition = "(" + topicCondition + ") and " + condition; - - return anEntityAdapter.getRelation( - condition, - "title", - "topic" ); - } - catch (Throwable t) { - throw new RuntimeException(t.getMessage()); - } - } - } - - protected class ContentToMediaField implements EntityAdapterDefinition.CalculatedField { - private String definition; - private boolean published; - - public ContentToMediaField(String aDefinition, boolean anOnlyPublished) { - definition = aDefinition; - published = anOnlyPublished; - } - - public ContentToMediaField(String aDefinition) { - this(aDefinition, true); - } - - public Object getValue(EntityAdapter anEntityAdapter) { - try { - String condition = "exists (select * from content_x_media where content_id="+anEntityAdapter.get("id")+" and media_id=id)"; - if (published) - condition = "is_published='t' and " + condition; - return anEntityAdapter.getRelation( - condition, - "id", - definition); - } - catch (Throwable t) { - throw new RuntimeException(t.getMessage()); - } - } - } - - protected class CommentToMediaField implements EntityAdapterDefinition.CalculatedField { - private String definition; - private boolean published; - - public CommentToMediaField(String aDefinition, boolean anOnlyPublished) { - definition = aDefinition; - published = anOnlyPublished; - } - - public CommentToMediaField(String aDefinition) { - this(aDefinition, true); - } - - public Object getValue(EntityAdapter anEntityAdapter) { - try { - String condition = "exists (select * from comment_x_media where comment_id="+anEntityAdapter.get("id")+" and media_id=id)"; - if (published) - condition = "is_published='t' and " + condition; - return anEntityAdapter.getRelation( - condition, - "id", - definition); - } - catch (Throwable t) { - throw new RuntimeException(t.getMessage()); - } - } - } - - protected class ContentToIconField implements EntityAdapterDefinition.CalculatedField { - public Object getValue(EntityAdapter anEntityAdapter) { - EntityAdapter media; - Entity mediaType; - RewindableIterator iterator; - Map result; - MirMedia mediaHandler; - String tinyIcon; - String iconAlt; - - try { - iterator = (RewindableIterator) (anEntityAdapter.get("to_uploaded_media")); - iterator.rewind(); - - tinyIcon = MirGlobal.config().getString("Producer.Icon.TinyText"); - iconAlt = "Text"; - - if (iterator.hasNext()) { - media = (EntityAdapter) iterator.next(); - - mediaType = ((EntityUploadedMedia) (media.getEntity())).getMediaType(); - mediaHandler = MediaHelper.getHandler( mediaType ); - - if (mediaHandler.isVideo()) { - tinyIcon = MirGlobal.config().getString("Producer.Icon.TinyVideo"); - iconAlt = "Video"; - } - else if (mediaHandler.isAudio()) { - tinyIcon = MirGlobal.config().getString("Producer.Icon.TinyAudio"); - iconAlt = "Audio"; - } - else if (mediaHandler.isImage()) { - tinyIcon = MirGlobal.config().getString("Producer.Icon.TinyImage"); - iconAlt = "Image"; - } - else { - tinyIcon = mediaHandler.getTinyIconName(); - iconAlt = mediaHandler.getIconAltName(); - } - - } - } - catch (Throwable t) { - logger.error("ContentToIconField: " +t.getMessage()); - throw new RuntimeException(t.getMessage()); - } - - result = new HashMap(); - result.put("tiny_icon", MirGlobal.config().getString("Producer.ImageRoot") + "/" + tinyIcon); - result.put("icon_alt", iconAlt); - - return result; - } - } - - protected class ContentCommentCountField implements EntityAdapterDefinition.CalculatedField { - private String extraCondition; - - public ContentCommentCountField(String anExtraCondition) { - super(); - - extraCondition = anExtraCondition; - } - - public Object getValue(EntityAdapter anEntityAdapter) { - try { - return Integer.toString( - DatabaseComment.getInstance().getSize( - "to_media="+anEntityAdapter.get("id")+" " + extraCondition)); - } - catch (Throwable t) { - throw new RuntimeException(t.getMessage()); - } - } - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, but you are not obligated to do so. + * If you do not wish to do so, delete this exception statement from your version. + */ +package mircoders.localizer.basic; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Vector; + +import mir.config.MirPropertiesConfiguration; +import mir.entity.Entity; +import mir.entity.adapter.EntityAdapter; +import mir.entity.adapter.EntityAdapterDefinition; +import mir.entity.adapter.EntityAdapterModel; +import mir.log.LoggerWrapper; +import mir.media.MediaHelper; +import mir.media.MirMedia; +import mir.util.ParameterExpander; +import mir.util.RewindableIterator; +import mir.util.StructuredContentParser; +import mircoders.entity.EntityUploadedMedia; +import mircoders.global.MirGlobal; +import mircoders.localizer.MirAdminInterfaceLocalizer; +import mircoders.localizer.MirDataModelLocalizer; +import mircoders.localizer.MirLocalizerExc; +import mircoders.localizer.MirLocalizerFailure; +import mircoders.storage.DatabaseArticleType; +import mircoders.storage.DatabaseAudio; +import mircoders.storage.DatabaseBreaking; +import mircoders.storage.DatabaseComment; +import mircoders.storage.DatabaseCommentStatus; +import mircoders.storage.DatabaseContent; +import mircoders.storage.DatabaseContentToMedia; +import mircoders.storage.DatabaseContentToTopics; +import mircoders.storage.DatabaseImageType; +import mircoders.storage.DatabaseImages; +import mircoders.storage.DatabaseLanguage; +import mircoders.storage.DatabaseMediaType; +import mircoders.storage.DatabaseMediafolder; +import mircoders.storage.DatabaseMessages; +import mircoders.storage.DatabaseOther; +import mircoders.storage.DatabaseTopics; +import mircoders.storage.DatabaseUploadedMedia; +import mircoders.storage.DatabaseUsers; +import mircoders.storage.DatabaseVideo; + +public class MirBasicDataModelLocalizer implements MirDataModelLocalizer { + protected LoggerWrapper logger; + protected MirPropertiesConfiguration configuration; + + public MirBasicDataModelLocalizer() throws MirLocalizerFailure, MirLocalizerExc { + logger = new LoggerWrapper("Localizer.DataModel"); + + try { + configuration = MirPropertiesConfiguration.instance(); + } + catch (Throwable e) { + throw new MirLocalizerFailure("Can't get configuration: " + e.getMessage(), e); + } + } + + protected void constructContentAdapterDefinition(EntityAdapterDefinition anEntityAdapterDefinition) throws MirLocalizerFailure, MirLocalizerExc { + try { + anEntityAdapterDefinition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone")); + anEntityAdapterDefinition.addDBDateField("changedate", "webdb_lastchange", configuration.getString("Mir.DefaultTimezone")); + anEntityAdapterDefinition.addMirDateField("date", "date", configuration.getString("Mir.DefaultTimezone")); + anEntityAdapterDefinition.addCalculatedField("to_topics", new ContentToTopicsField()); + anEntityAdapterDefinition.addCalculatedField("to_comments", new ContentToCommentsField()); + anEntityAdapterDefinition.addCalculatedField("language", new ContentToLanguageField()); + + anEntityAdapterDefinition.addCalculatedField("commentcount", new ContentCommentCountField(" and is_published='1'")); + anEntityAdapterDefinition.addCalculatedField("fullcommentcount", new ContentCommentCountField("")); + + anEntityAdapterDefinition.addCalculatedField("to_uploaded_media", new ContentToMediaField( "uploadedMedia" )); + anEntityAdapterDefinition.addCalculatedField("to_media_images", new ContentToMediaField( "image" )); + anEntityAdapterDefinition.addCalculatedField("to_media_audio", new ContentToMediaField( "audio" )); + anEntityAdapterDefinition.addCalculatedField("to_media_video", new ContentToMediaField( "video" )); + anEntityAdapterDefinition.addCalculatedField("to_media_other", new ContentToMediaField( "otherMedia" )); + anEntityAdapterDefinition.addCalculatedField("to_all_uploaded_media", new ContentToMediaField( "uploadedMedia", false)); + anEntityAdapterDefinition.addCalculatedField("to_all_media_images", new ContentToMediaField( "image", false)); + anEntityAdapterDefinition.addCalculatedField("to_all_media_audio", new ContentToMediaField( "audio", false)); + anEntityAdapterDefinition.addCalculatedField("to_all_media_video", new ContentToMediaField( "video", false)); + anEntityAdapterDefinition.addCalculatedField("to_all_media_other", new ContentToMediaField( "otherMedia", false)); + anEntityAdapterDefinition.addCalculatedField("to_media_icon", new ContentToIconField()); + + anEntityAdapterDefinition.addCalculatedField("article_type", new ContentToArticleTypeField()); + + anEntityAdapterDefinition.addCalculatedField("description_parsed", new FilteredField("description")); + anEntityAdapterDefinition.addCalculatedField("content_data_parsed", new FilteredField("content_data")); + + anEntityAdapterDefinition.addCalculatedField("children", new ContentToChildrenField()); + anEntityAdapterDefinition.addCalculatedField("parent", new ContentToParentField()); + + anEntityAdapterDefinition.addCalculatedField("publicurl", new ExpandedField(configuration.getString("Article.PublicUrl"))); + + anEntityAdapterDefinition.addCalculatedField("operations", + new EntityToSimpleOperationsField(MirGlobal.localizer().adminInterface().simpleArticleOperations())); + } + catch (Throwable t) { + throw new MirLocalizerFailure(t.getMessage(), t); + } + } + + protected void constructCommentAdapterDefinition(EntityAdapterDefinition anEntityAdapterDefinition) throws MirLocalizerFailure { + try { + anEntityAdapterDefinition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone")); + anEntityAdapterDefinition.addCalculatedField("to_content", new CommentToContentField()); + anEntityAdapterDefinition.addCalculatedField("status", new CommentToStatusField()); + + anEntityAdapterDefinition.addCalculatedField("to_uploaded_media", new CommentToMediaField( "uploadedMedia" )); + anEntityAdapterDefinition.addCalculatedField("to_media_images", new CommentToMediaField( "image" )); + anEntityAdapterDefinition.addCalculatedField("to_media_audio", new CommentToMediaField( "audio" )); + anEntityAdapterDefinition.addCalculatedField("to_media_video", new CommentToMediaField( "video" )); + anEntityAdapterDefinition.addCalculatedField("to_media_other", new CommentToMediaField( "otherMedia" )); + anEntityAdapterDefinition.addCalculatedField("to_all_uploaded_media", new CommentToMediaField( "uploadedMedia", false)); + anEntityAdapterDefinition.addCalculatedField("to_all_media_images", new CommentToMediaField( "image", false)); + anEntityAdapterDefinition.addCalculatedField("to_all_media_audio", new CommentToMediaField( "audio", false)); + anEntityAdapterDefinition.addCalculatedField("to_all_media_video", new CommentToMediaField( "video", false)); + anEntityAdapterDefinition.addCalculatedField("to_all_media_other", new CommentToMediaField( "otherMedia", false)); + + anEntityAdapterDefinition.addCalculatedField("publicurl", new ExpandedField(configuration.getString("Comment.PublicUrl"))); + + anEntityAdapterDefinition.addCalculatedField("description_parsed", new FilteredField("description")); + anEntityAdapterDefinition.addCalculatedField("operations", + new EntityToSimpleOperationsField(MirGlobal.localizer().adminInterface().simpleCommentOperations())); + } + catch (Throwable t) { + throw new MirLocalizerFailure(t.getMessage(), t); + } + } + + public EntityAdapterModel adapterModel() throws MirLocalizerFailure, MirLocalizerExc { + EntityAdapterModel result = new EntityAdapterModel(); + + try { + EntityAdapterDefinition definition; + + definition = new EntityAdapterDefinition(); + constructContentAdapterDefinition( definition ); + result.addMapping( "content", DatabaseContent.getInstance(), definition); + + definition = new EntityAdapterDefinition(); + constructCommentAdapterDefinition( definition ); + result.addMapping( "comment", DatabaseComment.getInstance(), definition); + + result.addMapping( "articleType", DatabaseArticleType.getInstance(), new EntityAdapterDefinition()); + result.addMapping( "commentStatus", DatabaseCommentStatus.getInstance(), new EntityAdapterDefinition()); + + definition = new EntityAdapterDefinition(); + definition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone")); + result.addMapping( "breakingNews", DatabaseBreaking.getInstance(), definition); + + definition = new EntityAdapterDefinition(); + definition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone")); + result.addMapping( "internalMessage", DatabaseMessages.getInstance(), definition); + + definition = new EntityAdapterDefinition(); + definition.addCalculatedField("mediafolder", new MediaToMediaFolderField()); + result.addMapping( "uploadedMedia", DatabaseUploadedMedia.getInstance(), definition); + definition = new EntityAdapterDefinition(); + definition.addCalculatedField("mediafolder", new MediaToMediaFolderField()); + result.addMapping( "image", DatabaseImages.getInstance(), definition); + definition = new EntityAdapterDefinition(); + definition.addCalculatedField("mediafolder", new MediaToMediaFolderField()); + result.addMapping( "audio", DatabaseAudio.getInstance(), definition); + definition = new EntityAdapterDefinition(); + definition.addCalculatedField("mediafolder", new MediaToMediaFolderField()); + result.addMapping( "video", DatabaseVideo.getInstance(), definition); + definition = new EntityAdapterDefinition(); + definition.addCalculatedField("mediafolder", new MediaToMediaFolderField()); + result.addMapping( "otherMedia", DatabaseOther.getInstance(), definition); + + + result.addMapping( "mediaFolder", DatabaseMediafolder.getInstance(), new EntityAdapterDefinition()); + result.addMapping( "imageType", DatabaseImageType.getInstance(), new EntityAdapterDefinition()); + result.addMapping( "language", DatabaseLanguage.getInstance(), new EntityAdapterDefinition()); + result.addMapping( "mediaType", DatabaseMediaType.getInstance(), new EntityAdapterDefinition()); + result.addMapping( "topic", DatabaseTopics.getInstance(), new EntityAdapterDefinition()); + result.addMapping( "user", DatabaseUsers.getInstance(), new EntityAdapterDefinition()); + result.addMapping( "otherMedia", DatabaseOther.getInstance(), new EntityAdapterDefinition()); + + result.addMapping( "content_x_topic", DatabaseContentToTopics.getInstance(), new EntityAdapterDefinition()); + + } + catch (Throwable t) { + throw new MirLocalizerFailure(t.getMessage(), t); + } + + return result; + } + + protected class CommentToContentField implements EntityAdapterDefinition.CalculatedField { + public Object getValue(EntityAdapter anEntityAdapter) { + try { + return anEntityAdapter.getToOneRelation( + "id="+anEntityAdapter.get("to_media"), + "id", + "content" ); + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + } + + protected class CommentToStatusField implements EntityAdapterDefinition.CalculatedField { + public Object getValue(EntityAdapter anEntityAdapter) { + try { + return anEntityAdapter.getToOneRelation( + "id="+anEntityAdapter.get("to_comment_status"), + "id", + "commentStatus" ); + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + } + + protected class EntityToSimpleOperationsField implements EntityAdapterDefinition.CalculatedField { + private List operations; + + public EntityToSimpleOperationsField(List anOperations) { + operations = anOperations; + } + + public Object getValue(EntityAdapter anEntityAdapter) { + try { + Iterator i = operations.iterator(); + List availableOperations = new Vector(); + + while (i.hasNext()) { + MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = + (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next(); + + if (operation.isAvailable(anEntityAdapter)) { + availableOperations.add(operation.getName()); + } + }; + + return availableOperations; + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + } + + protected class FilteredField implements EntityAdapterDefinition.CalculatedField { + private String fieldName; + + public FilteredField(String aFieldName) { + fieldName = aFieldName; + } + + public Object getValue(EntityAdapter anEntityAdapter) { + try { + if (anEntityAdapter.get("is_html")!=null && anEntityAdapter.get("is_html").equals("1")) { + return MirGlobal.localizer().producerAssistant().filterHTMLText((String) anEntityAdapter.get(fieldName)); + } + else { + return MirGlobal.localizer().producerAssistant().filterNonHTMLText((String) anEntityAdapter.get(fieldName)); + } + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + } + + protected class StructuredContentField implements EntityAdapterDefinition.CalculatedField { + private String expression; + + public StructuredContentField(String anExpression) { + expression = anExpression; + } + + public Object getValue(EntityAdapter anEntityAdapter) { + try { + return StructuredContentParser.parse(ParameterExpander.evaluateStringExpression(anEntityAdapter, expression)); + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + } + + protected class ExpandedField implements EntityAdapterDefinition.CalculatedField { + private String expression; + + public ExpandedField(String anExpression) { + expression = anExpression; + } + + public Object getValue(EntityAdapter anEntityAdapter) { + try { + return ParameterExpander.expandExpression(anEntityAdapter, expression); + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + } + + protected class EvaluatedField implements EntityAdapterDefinition.CalculatedField { + private String expression; + + public EvaluatedField(String anExpression) { + expression = anExpression; + } + + public Object getValue(EntityAdapter anEntityAdapter) { + try { + return ParameterExpander.evaluateExpression(anEntityAdapter, expression); + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + } + + protected class ContentToParentField implements EntityAdapterDefinition.CalculatedField { + public Object getValue(EntityAdapter anEntityAdapter) { + try { + logger.debug("ContentToParentField.getValue"); + return anEntityAdapter.getToOneRelation( + "id="+anEntityAdapter.get("to_content"), + "id", + "content" ); + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + } + + protected class ContentToChildrenField implements EntityAdapterDefinition.CalculatedField { + public Object getValue(EntityAdapter anEntityAdapter) { + try { + return anEntityAdapter.getRelation( + "to_content="+anEntityAdapter.get("id"), + "id", + "content" ); + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + } + + protected class ContentToLanguageField implements EntityAdapterDefinition.CalculatedField { + public Object getValue(EntityAdapter anEntityAdapter) { + try { + return anEntityAdapter.getToOneRelation( + "id="+anEntityAdapter.get("to_language"), + "id", + "language" ); + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + } + + protected class ContentToArticleTypeField implements EntityAdapterDefinition.CalculatedField { + public Object getValue(EntityAdapter anEntityAdapter) { + try { + return anEntityAdapter.getToOneRelation( + "id="+anEntityAdapter.get("to_article_type"), + "id", + "articleType" ); + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + } + + protected class MediaToMediaFolderField implements EntityAdapterDefinition.CalculatedField { + public Object getValue(EntityAdapter anEntityAdapter) { + try { + return anEntityAdapter.getToOneRelation( + "id="+anEntityAdapter.get("to_media_folder"), + "id", + "mediaFolder" ); + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + } + + protected class ContentToCommentsField implements EntityAdapterDefinition.CalculatedField { + private String extracondition; + private String order; + + public ContentToCommentsField() { + this ( " and is_published='1'", "webdb_create"); + } + + public ContentToCommentsField(String anExtraCondition, String anOrder) { + order = anOrder; + extracondition = anExtraCondition; + } + + public Object getValue(EntityAdapter anEntityAdapter) { + try { + return anEntityAdapter.getRelation( + "to_media="+anEntityAdapter.get("id")+" " + extracondition, + order, + "comment" ); + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + } + + protected class ContentToTopicsField implements EntityAdapterDefinition.CalculatedField { + private String topicCondition; + + public ContentToTopicsField() { + this(null); + } + + public ContentToTopicsField(String aTopicCondition) { + topicCondition = aTopicCondition; + } + + public Object getValue(EntityAdapter anEntityAdapter) { + try { + String condition = "exists (select * from content_x_topic where content_id="+anEntityAdapter.get("id")+" and topic_id=id)"; + if (topicCondition!=null && topicCondition.length()>0) + condition = "(" + topicCondition + ") and " + condition; + + return anEntityAdapter.getRelation( + condition, + "title", + "topic" ); + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + } + + protected class ContentToMediaField implements EntityAdapterDefinition.CalculatedField { + private String definition; + private boolean published; + + public ContentToMediaField(String aDefinition, boolean anOnlyPublished) { + definition = aDefinition; + published = anOnlyPublished; + } + + public ContentToMediaField(String aDefinition) { + this(aDefinition, true); + } + + public Object getValue(EntityAdapter anEntityAdapter) { + try { + String condition = "exists (select * from content_x_media where content_id="+anEntityAdapter.get("id")+" and media_id=id)"; + if (published) + condition = "is_published='t' and " + condition; + return anEntityAdapter.getRelation( + condition, + "id", + definition); + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + } + + protected class CommentToMediaField implements EntityAdapterDefinition.CalculatedField { + private String definition; + private boolean published; + + public CommentToMediaField(String aDefinition, boolean anOnlyPublished) { + definition = aDefinition; + published = anOnlyPublished; + } + + public CommentToMediaField(String aDefinition) { + this(aDefinition, true); + } + + public Object getValue(EntityAdapter anEntityAdapter) { + try { + String condition = "exists (select * from comment_x_media where comment_id="+anEntityAdapter.get("id")+" and media_id=id)"; + if (published) + condition = "is_published='t' and " + condition; + return anEntityAdapter.getRelation( + condition, + "id", + definition); + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + } + + protected class ContentToIconField implements EntityAdapterDefinition.CalculatedField { + public Object getValue(EntityAdapter anEntityAdapter) { + EntityAdapter media; + Entity mediaType; + RewindableIterator iterator; + Map result; + MirMedia mediaHandler; + String tinyIcon; + String iconAlt; + + try { + iterator = (RewindableIterator) (anEntityAdapter.get("to_uploaded_media")); + iterator.rewind(); + + tinyIcon = MirGlobal.config().getString("Producer.Icon.TinyText"); + iconAlt = "Text"; + + if (iterator.hasNext()) { + media = (EntityAdapter) iterator.next(); + + mediaType = ((EntityUploadedMedia) (media.getEntity())).getMediaType(); + mediaHandler = MediaHelper.getHandler( mediaType ); + + if (mediaHandler.isVideo()) { + tinyIcon = MirGlobal.config().getString("Producer.Icon.TinyVideo"); + iconAlt = "Video"; + } + else if (mediaHandler.isAudio()) { + tinyIcon = MirGlobal.config().getString("Producer.Icon.TinyAudio"); + iconAlt = "Audio"; + } + else if (mediaHandler.isImage()) { + tinyIcon = MirGlobal.config().getString("Producer.Icon.TinyImage"); + iconAlt = "Image"; + } + else { + tinyIcon = mediaHandler.getTinyIconName(); + iconAlt = mediaHandler.getIconAltName(); + } + + } + } + catch (Throwable t) { + logger.error("ContentToIconField: " +t.getMessage()); + throw new RuntimeException(t.getMessage()); + } + + result = new HashMap(); + result.put("tiny_icon", MirGlobal.config().getString("Producer.ImageRoot") + "/" + tinyIcon); + result.put("icon_alt", iconAlt); + + return result; + } + } + + protected class ContentCommentCountField implements EntityAdapterDefinition.CalculatedField { + private String extraCondition; + + public ContentCommentCountField(String anExtraCondition) { + super(); + + extraCondition = anExtraCondition; + } + + public Object getValue(EntityAdapter anEntityAdapter) { + try { + return Integer.toString( + DatabaseComment.getInstance().getSize( + "to_media="+anEntityAdapter.get("id")+" " + extraCondition)); + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + } + + protected class ContentMediaCountField implements EntityAdapterDefinition.CalculatedField { + private String table; + private boolean published; + + public ContentMediaCountField(String aTable, boolean anOnlyPublished) { + table = aTable; + published = anOnlyPublished; + } + + public ContentMediaCountField(String aTable) { + this(aTable, true); + } + + public Object getValue(EntityAdapter anEntityAdapter) { + try { + String subQuery = "select * from "+table+" where id = media_id"; + if (published) + subQuery = subQuery + " and is_published='t'"; + + return Integer.toString( + DatabaseContentToMedia.getInstance().getSize( + "exists ("+subQuery+")")); + } + catch (Throwable t) { + throw new RuntimeException(t.getMessage()); + } + } + } +} diff --git a/source/mircoders/media/MediaHandlerGeneric.java b/source/mircoders/media/MediaHandlerGeneric.java index 9e800688..3d531ab8 100755 --- a/source/mircoders/media/MediaHandlerGeneric.java +++ b/source/mircoders/media/MediaHandlerGeneric.java @@ -29,20 +29,20 @@ */ package mircoders.media; -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import javax.servlet.ServletContext; - -import freemarker.template.SimpleList; - -import mir.config.MirPropertiesConfiguration; -import mir.entity.Entity; -import mir.log.LoggerWrapper; -import mir.media.MediaExc; -import mir.media.MediaFailure; -import mir.media.MirMedia; -import mir.misc.FileUtil; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.util.List; +import java.util.Vector; +import javax.servlet.ServletContext; + +import mir.config.MirPropertiesConfiguration; +import mir.entity.Entity; +import mir.log.LoggerWrapper; +import mir.media.MediaExc; +import mir.media.MediaFailure; +import mir.media.MirMedia; +import mir.misc.FileUtil; import mir.misc.StringUtil; @@ -63,7 +63,7 @@ import mir.misc.StringUtil; * * @see mir.media.MirMedia * @author mh - * @version $Id: MediaHandlerGeneric.java,v 1.20.2.1 2003/08/04 20:03:25 zapata Exp $ + * @version $Id: MediaHandlerGeneric.java,v 1.20.2.2 2003/09/03 17:49:39 zapata Exp $ */ public class MediaHandlerGeneric implements MirMedia @@ -177,9 +177,9 @@ public class MediaHandlerGeneric implements MirMedia return "Generic media"; } - public SimpleList getURL(Entity ent, Entity mediaTypeEnt) + public List getURL(Entity ent, Entity mediaTypeEnt) { - SimpleList theList = new SimpleList(); + List theList = new Vector(); theList.add(ent); return theList; } diff --git a/source/mircoders/media/MediaHandlerImages.java b/source/mircoders/media/MediaHandlerImages.java index 210ad37e..18b35323 100755 --- a/source/mircoders/media/MediaHandlerImages.java +++ b/source/mircoders/media/MediaHandlerImages.java @@ -31,6 +31,7 @@ package mircoders.media; import java.io.File; import java.io.InputStream; +import java.util.*; import mir.config.MirPropertiesConfiguration; import mir.config.MirPropertiesConfiguration.PropertiesConfigExc; @@ -42,7 +43,6 @@ import mir.media.MirMedia; import mir.misc.FileUtil; import mir.misc.StringUtil; import mircoders.entity.EntityImages; -import freemarker.template.SimpleList; /** * This class handles saving, fetching creating representations @@ -58,7 +58,7 @@ import freemarker.template.SimpleList; * * @see mir.media.MirMedia * @author mh - * @version $Id: MediaHandlerImages.java,v 1.23 2003/04/30 00:37:27 zapata Exp $ + * @version $Id: MediaHandlerImages.java,v 1.23.2.1 2003/09/03 17:49:39 zapata Exp $ */ @@ -161,8 +161,8 @@ public abstract class MediaHandlerImages implements MirMedia return in; } - public SimpleList getURL(Entity ent, Entity mediaTypeEnt) { - SimpleList theList = new SimpleList(); + public List getURL(Entity ent, Entity mediaTypeEnt) { + List theList = new Vector(); theList.add(ent); return theList; } diff --git a/source/mircoders/media/MediaHandlerMp3.java b/source/mircoders/media/MediaHandlerMp3.java index f69cec8b..81bf55a5 100755 --- a/source/mircoders/media/MediaHandlerMp3.java +++ b/source/mircoders/media/MediaHandlerMp3.java @@ -1,141 +1,143 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with any library licensed under the Apache Software License, - * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library - * (or with modified versions of the above that use the same license as the above), - * and distribute linked combinations including the two. You must obey the - * GNU General Public License in all respects for all of the code used other than - * the above mentioned libraries. If you modify this file, you may extend this - * exception to your version of the file, but you are not obligated to do so. - * If you do not wish to do so, delete this exception statement from your version. - */ -package mircoders.media; - -import java.io.StringReader; - -import mir.entity.Entity; -import mir.log.LoggerWrapper; -import mir.media.MediaExc; -import mir.media.MediaFailure; -import mir.media.MirMedia; -import mir.misc.FileUtil; -import mir.misc.StringUtil; -import freemarker.template.SimpleHash; -import freemarker.template.SimpleList; - -/** - * Please note: this media handler produces - * 3 media files, the raw .mp3, a .m3u which is - * contains the URL for the mp3 and a .pls which - * contains the URL to the mp3 in shoutcast playlist - * format. What's important is that the web server (of - * the media host) must recognize the .m3u and .pls file - * extensions and send the proper "audio/x-mpegurl" - * and "audio/x-scpls" mime-types respectively. - * If the web server is apache, it's easy, just - * add: - * - * audio/x-mpegurl m3u - * audio/x-scpl pls - * - * to the file pointed to by the "TypesConfig" - * command in your apache config file. Or add - * and equivalent AddType command to your httpd.conf. - * Of course this assumes that the mod_mime is loaded. - * - * If the web server is not apache, then your on your own. - * - * @see mir.media.MirMedia - * @author mh - * @version $Id: MediaHandlerMp3.java,v 1.15 2003/04/21 12:42:48 idfx Exp $ - */ - -public class MediaHandlerMp3 extends MediaHandlerAudio implements MirMedia -{ - protected LoggerWrapper logger; - - public MediaHandlerMp3() { - logger = new LoggerWrapper("Media.Audio.Mp3"); - } - - public void produce(Entity ent, Entity mediaTypeEnt) throws MediaExc, MediaFailure { - - // first check if the file exists - super.produce(ent, mediaTypeEnt); - - String baseName = ent.getId(); - String date = ent.getValue("date"); - String datePath = StringUtil.webdbDate2path(date); - String mp3Pointer = getPublishHost() + ent.getValue("publish_path"); - String mpegURLFile = baseName + ".m3u"; - String playlistFile = baseName + ".pls"; - - try { - //write the "meta" files - //first the .m3u since it only contains one line - FileUtil.write(getStoragePath() + "/" + datePath + "/" + mpegURLFile, - new StringReader(mp3Pointer), "US-ASCII"); - //now the .pls file - FileUtil.write(getStoragePath() + "/" + datePath + "/" + playlistFile, - new StringReader(mp3Pointer), "US-ASCII"); - } - catch (Throwable e) { - logger.error("MediaHandlerMp3.produce: " + e.toString()); - - throw new MediaFailure(e); - } - } - - public SimpleList getURL(Entity ent, Entity mediaTypeEnt) { - SimpleList theList = new SimpleList(); - - //String stringSize = ent.getValue("size"); - //int size = Integer.parseInt(stringSize, 10)/1024; - theList.add(ent); - - String basePath = StringUtil.regexpReplace(ent.getValue("publish_path"), - ".mp3$", ""); - - // @todo the texts ("title") below urgently need to be sanely localizaeble - // somehow - SimpleHash m3uHash = new SimpleHash(); - m3uHash.put("publish_path", basePath + ".m3u"); - m3uHash.put("publish_server", ent.getValue("publish_server")); - m3uHash.put("title", "stream URL"); - theList.add(m3uHash); - - SimpleHash plsHash = new SimpleHash(); - plsHash.put("publish_path", basePath + ".pls"); - plsHash.put("publish_server", ent.getValue("publish_server")); - plsHash.put("title", "playlist URL"); - theList.add(plsHash); - - return theList; - - } - - public String getDescr(Entity mediaType) { - return "mp3"; - } -} - - - +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, but you are not obligated to do so. + * If you do not wish to do so, delete this exception statement from your version. + */ +package mircoders.media; + +import java.io.StringReader; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Vector; + +import mir.entity.Entity; +import mir.log.LoggerWrapper; +import mir.media.MediaExc; +import mir.media.MediaFailure; +import mir.media.MirMedia; +import mir.misc.FileUtil; +import mir.misc.StringUtil; + +/** + * Please note: this media handler produces + * 3 media files, the raw .mp3, a .m3u which is + * contains the URL for the mp3 and a .pls which + * contains the URL to the mp3 in shoutcast playlist + * format. What's important is that the web server (of + * the media host) must recognize the .m3u and .pls file + * extensions and send the proper "audio/x-mpegurl" + * and "audio/x-scpls" mime-types respectively. + * If the web server is apache, it's easy, just + * add: + * + * audio/x-mpegurl m3u + * audio/x-scpl pls + * + * to the file pointed to by the "TypesConfig" + * command in your apache config file. Or add + * and equivalent AddType command to your httpd.conf. + * Of course this assumes that the mod_mime is loaded. + * + * If the web server is not apache, then your on your own. + * + * @see mir.media.MirMedia + * @author mh + * @version $Id: MediaHandlerMp3.java,v 1.15.2.1 2003/09/03 17:49:39 zapata Exp $ + */ + +public class MediaHandlerMp3 extends MediaHandlerAudio implements MirMedia +{ + protected LoggerWrapper logger; + + public MediaHandlerMp3() { + logger = new LoggerWrapper("Media.Audio.Mp3"); + } + + public void produce(Entity ent, Entity mediaTypeEnt) throws MediaExc, MediaFailure { + + // first check if the file exists + super.produce(ent, mediaTypeEnt); + + String baseName = ent.getId(); + String date = ent.getValue("date"); + String datePath = StringUtil.webdbDate2path(date); + String mp3Pointer = getPublishHost() + ent.getValue("publish_path"); + String mpegURLFile = baseName + ".m3u"; + String playlistFile = baseName + ".pls"; + + try { + //write the "meta" files + //first the .m3u since it only contains one line + FileUtil.write(getStoragePath() + "/" + datePath + "/" + mpegURLFile, + new StringReader(mp3Pointer), "US-ASCII"); + //now the .pls file + FileUtil.write(getStoragePath() + "/" + datePath + "/" + playlistFile, + new StringReader(mp3Pointer), "US-ASCII"); + } + catch (Throwable e) { + logger.error("MediaHandlerMp3.produce: " + e.toString()); + + throw new MediaFailure(e); + } + } + + public List getURL(Entity ent, Entity mediaTypeEnt) { + List theList = new Vector(); + + //String stringSize = ent.getValue("size"); + //int size = Integer.parseInt(stringSize, 10)/1024; + theList.add(ent); + + String basePath = StringUtil.regexpReplace(ent.getValue("publish_path"), + ".mp3$", ""); + + // @todo the texts ("title") below urgently need to be sanely localizaeble + // somehow + Map m3uHash = new HashMap(); + m3uHash.put("publish_path", basePath + ".m3u"); + m3uHash.put("publish_server", ent.getValue("publish_server")); + m3uHash.put("title", "stream URL"); + theList.add(m3uHash); + + Map plsHash = new HashMap(); + plsHash.put("publish_path", basePath + ".pls"); + plsHash.put("publish_server", ent.getValue("publish_server")); + plsHash.put("title", "playlist URL"); + theList.add(plsHash); + + return theList; + + } + + public String getDescr(Entity mediaType) { + return "mp3"; + } +} + + + diff --git a/source/mircoders/media/MediaHandlerRealAudio.java b/source/mircoders/media/MediaHandlerRealAudio.java index 62dc5a2b..a2c9e087 100755 --- a/source/mircoders/media/MediaHandlerRealAudio.java +++ b/source/mircoders/media/MediaHandlerRealAudio.java @@ -1,128 +1,130 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with any library licensed under the Apache Software License, - * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library - * (or with modified versions of the above that use the same license as the above), - * and distribute linked combinations including the two. You must obey the - * GNU General Public License in all respects for all of the code used other than - * the above mentioned libraries. If you modify this file, you may extend this - * exception to your version of the file, but you are not obligated to do so. - * If you do not wish to do so, delete this exception statement from your version. - */ -package mircoders.media; - -import java.io.StringReader; - -import mir.entity.Entity; -import mir.log.LoggerWrapper; -import mir.media.MediaExc; -import mir.media.MediaFailure; -import mir.media.MirMedia; -import mir.misc.FileUtil; -import mir.misc.StringUtil; -import freemarker.template.SimpleHash; -import freemarker.template.SimpleList; - - - -/** - * Handles realAudio .it manages the ram file. - * - * 03.2002 - reworked Realmedia handling. -mh - * - * @see mir.media.MediaHandlerGeneric - * @see mir.media.MirMedia - * @author john , mh - * @version $Id: MediaHandlerRealAudio.java,v 1.19 2003/04/21 12:42:48 idfx Exp $ - */ - - -public class MediaHandlerRealAudio extends MediaHandlerAudio implements MirMedia -{ - public MediaHandlerRealAudio() { - logger = new LoggerWrapper("Media.Audio.Real"); - } - - public void produce (Entity ent, Entity mediaTypeEnt ) throws MediaExc, MediaFailure { - - // first see if the file exists - super.produce(ent, mediaTypeEnt); - - String baseName = ent.getId(); - String date = ent.getValue("date"); - String datePath = StringUtil.webdbDate2path(date); - String rtspDir = configuration.getString("Producer.RealMedia.Path"); - String rtspMediaHost = configuration.getString("Producer.RealMedia.Host"); - - String RealMediaPointer = rtspMediaHost+ent.getValue("publish_path"); - String RealMediaFile = datePath+ent.getId()+".ram"; - try { - //write an rm (ram?. -mh) file - FileUtil.write(super.getStoragePath()+"/"+RealMediaFile, - new StringReader(RealMediaPointer), "US-ASCII"); - } - catch (Throwable e) { - logger.error("MediaHandlerRealAudio.produce: " + e.toString()); - throw new MediaFailure(e); - } - } - - public SimpleList getURL(Entity ent, Entity mediaTypeEnt) - { - SimpleList theList = new SimpleList(); - - //String stringSize = ent.getValue("size"); - //int size = Integer.parseInt(stringSize, 10)/1024; - theList.add(ent); - - String basePath=StringUtil.regexpReplace(ent.getValue("publish_path"), - ".ra$",""); - - // @todo the texts ("title") below urgently need to be sanely localizaeble - // somehow - SimpleHash ramHash = new SimpleHash(); - ramHash.put("publish_path", basePath+".ram"); - ramHash.put("publish_server", configuration.getString("Producer.Media.Host")); - ramHash.put("title", "stream URL"); - theList.add(ramHash); - - return theList; - } - - public String getStoragePath() - { - return configuration.getString("Producer.RealMedia.Path"); - } - - public String getDescr(Entity mediaType) - { - return "RealMedia"; - } - - public String getPublishHost() - { - return StringUtil.removeSlash(configuration.getString("Producer.RealMedia.Host")); - } - -} - - - +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, but you are not obligated to do so. + * If you do not wish to do so, delete this exception statement from your version. + */ +package mircoders.media; + +import java.io.StringReader; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Vector; + +import mir.entity.Entity; +import mir.log.LoggerWrapper; +import mir.media.MediaExc; +import mir.media.MediaFailure; +import mir.media.MirMedia; +import mir.misc.FileUtil; +import mir.misc.StringUtil; + + + +/** + * Handles realAudio .it manages the ram file. + * + * 03.2002 - reworked Realmedia handling. -mh + * + * @see mir.media.MediaHandlerGeneric + * @see mir.media.MirMedia + * @author john , mh + * @version $Id: MediaHandlerRealAudio.java,v 1.19.2.1 2003/09/03 17:49:40 zapata Exp $ + */ + + +public class MediaHandlerRealAudio extends MediaHandlerAudio implements MirMedia +{ + public MediaHandlerRealAudio() { + logger = new LoggerWrapper("Media.Audio.Real"); + } + + public void produce (Entity ent, Entity mediaTypeEnt ) throws MediaExc, MediaFailure { + + // first see if the file exists + super.produce(ent, mediaTypeEnt); + + String baseName = ent.getId(); + String date = ent.getValue("date"); + String datePath = StringUtil.webdbDate2path(date); + String rtspDir = configuration.getString("Producer.RealMedia.Path"); + String rtspMediaHost = configuration.getString("Producer.RealMedia.Host"); + + String RealMediaPointer = rtspMediaHost+ent.getValue("publish_path"); + String RealMediaFile = datePath+ent.getId()+".ram"; + try { + //write an rm (ram?. -mh) file + FileUtil.write(super.getStoragePath()+"/"+RealMediaFile, + new StringReader(RealMediaPointer), "US-ASCII"); + } + catch (Throwable e) { + logger.error("MediaHandlerRealAudio.produce: " + e.toString()); + throw new MediaFailure(e); + } + } + + public List getURL(Entity ent, Entity mediaTypeEnt) + { + List theList = new Vector(); + + //String stringSize = ent.getValue("size"); + //int size = Integer.parseInt(stringSize, 10)/1024; + theList.add(ent); + + String basePath=StringUtil.regexpReplace(ent.getValue("publish_path"), + ".ra$",""); + + // @todo the texts ("title") below urgently need to be sanely localizaeble + // somehow + Map ramHash = new HashMap(); + ramHash.put("publish_path", basePath+".ram"); + ramHash.put("publish_server", configuration.getString("Producer.Media.Host")); + ramHash.put("title", "stream URL"); + theList.add(ramHash); + + return theList; + } + + public String getStoragePath() + { + return configuration.getString("Producer.RealMedia.Path"); + } + + public String getDescr(Entity mediaType) + { + return "RealMedia"; + } + + public String getPublishHost() + { + return StringUtil.removeSlash(configuration.getString("Producer.RealMedia.Host")); + } + +} + + + diff --git a/source/mircoders/media/MediaHandlerRealVideo.java b/source/mircoders/media/MediaHandlerRealVideo.java index 947a9053..12af17f6 100755 --- a/source/mircoders/media/MediaHandlerRealVideo.java +++ b/source/mircoders/media/MediaHandlerRealVideo.java @@ -1,128 +1,130 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with any library licensed under the Apache Software License, - * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library - * (or with modified versions of the above that use the same license as the above), - * and distribute linked combinations including the two. You must obey the - * GNU General Public License in all respects for all of the code used other than - * the above mentioned libraries. If you modify this file, you may extend this - * exception to your version of the file, but you are not obligated to do so. - * If you do not wish to do so, delete this exception statement from your version. - */ -package mircoders.media; - -import java.io.File; -import java.io.StringReader; - -import mir.entity.Entity; -import mir.log.LoggerWrapper; -import mir.media.MediaExc; -import mir.media.MediaFailure; -import mir.media.MirMedia; -import mir.misc.FileUtil; -import mir.misc.StringUtil; -import freemarker.template.SimpleHash; -import freemarker.template.SimpleList; - - - -/** - * Handles realVideo .it manages the ram file. - * - * 03.2002 - reworked Realmedia handling. -mh - * - * @see mir.media.MediaHandlerGeneric - * @see mir.media.MirMedia - * @author john , mh - * @version $Id: MediaHandlerRealVideo.java,v 1.19 2003/04/21 12:42:48 idfx Exp $ - */ - - -public class MediaHandlerRealVideo extends MediaHandlerVideo implements MirMedia -{ - protected LoggerWrapper logger; - - public MediaHandlerRealVideo() { - logger = new LoggerWrapper("Media.Video.Real"); - } - - public void produce (Entity ent, Entity mediaTypeEnt) throws MediaExc, MediaFailure { - // first see if the file exists - super.produce(ent, mediaTypeEnt); - - String baseName = ent.getId(); - String date = ent.getValue("date"); - String datePath = StringUtil.webdbDate2path(date); - String rtspDir = configuration.getString("Producer.RealMedia.Path"); - String rtspMediaHost = configuration.getString("Producer.RealMedia.Host"); - - String RealMediaPointer = rtspMediaHost+ent.getValue("publish_path"); - String RealMediaFile = datePath+ent.getId()+".ram"; - try { - //write an rm (ram?. -mh) file - FileUtil.write(super.getStoragePath()+File.separator+RealMediaFile, - new StringReader(RealMediaPointer), "US-ASCII"); - } - catch (Throwable e) { - logger.error("MediaHandlerRealVideo.produce: " + e.toString()); - - throw new MediaFailure(e); - } - } - - public SimpleList getURL(Entity ent, Entity mediaTypeEnt) { - SimpleList theList = new SimpleList(); - - //String stringSize = ent.getValue("size"); - //int size = Integer.parseInt(stringSize, 10)/1024; - theList.add(ent); - - String basePath=StringUtil.regexpReplace(ent.getValue("publish_path"), - ".rm$",""); - - // @todo the texts ("title") below urgently need to be sanely localizaeble - // somehow - SimpleHash ramHash = new SimpleHash(); - ramHash.put("publish_path", basePath+".ram"); - ramHash.put("publish_server", configuration.getString("Producer.Media.Host")); - ramHash.put("title", "stream URL"); - theList.add(ramHash); - - return theList; - - } - - public String getStoragePath() { - return configuration.getString("Producer.RealMedia.Path"); - } - - public String getDescr(Entity mediaType) { - return "RealMedia"; - } - - public String getPublishHost() { - return StringUtil.removeSlash(configuration.getString("Producer.RealMedia.Host")); - } - -} - - - +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, but you are not obligated to do so. + * If you do not wish to do so, delete this exception statement from your version. + */ +package mircoders.media; + +import java.io.File; +import java.io.StringReader; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Vector; + +import mir.entity.Entity; +import mir.log.LoggerWrapper; +import mir.media.MediaExc; +import mir.media.MediaFailure; +import mir.media.MirMedia; +import mir.misc.FileUtil; +import mir.misc.StringUtil; + + + +/** + * Handles realVideo .it manages the ram file. + * + * 03.2002 - reworked Realmedia handling. -mh + * + * @see mir.media.MediaHandlerGeneric + * @see mir.media.MirMedia + * @author john , mh + * @version $Id: MediaHandlerRealVideo.java,v 1.19.2.1 2003/09/03 17:49:40 zapata Exp $ + */ + + +public class MediaHandlerRealVideo extends MediaHandlerVideo implements MirMedia +{ + protected LoggerWrapper logger; + + public MediaHandlerRealVideo() { + logger = new LoggerWrapper("Media.Video.Real"); + } + + public void produce (Entity ent, Entity mediaTypeEnt) throws MediaExc, MediaFailure { + // first see if the file exists + super.produce(ent, mediaTypeEnt); + + String baseName = ent.getId(); + String date = ent.getValue("date"); + String datePath = StringUtil.webdbDate2path(date); + String rtspDir = configuration.getString("Producer.RealMedia.Path"); + String rtspMediaHost = configuration.getString("Producer.RealMedia.Host"); + + String RealMediaPointer = rtspMediaHost+ent.getValue("publish_path"); + String RealMediaFile = datePath+ent.getId()+".ram"; + try { + //write an rm (ram?. -mh) file + FileUtil.write(super.getStoragePath()+File.separator+RealMediaFile, + new StringReader(RealMediaPointer), "US-ASCII"); + } + catch (Throwable e) { + logger.error("MediaHandlerRealVideo.produce: " + e.toString()); + + throw new MediaFailure(e); + } + } + + public List getURL(Entity ent, Entity mediaTypeEnt) { + List theList = new Vector(); + + //String stringSize = ent.getValue("size"); + //int size = Integer.parseInt(stringSize, 10)/1024; + theList.add(ent); + + String basePath=StringUtil.regexpReplace(ent.getValue("publish_path"), + ".rm$",""); + + // @todo the texts ("title") below urgently need to be sanely localizaeble + // somehow + Map ramHash = new HashMap(); + ramHash.put("publish_path", basePath+".ram"); + ramHash.put("publish_server", configuration.getString("Producer.Media.Host")); + ramHash.put("title", "stream URL"); + theList.add(ramHash); + + return theList; + + } + + public String getStoragePath() { + return configuration.getString("Producer.RealMedia.Path"); + } + + public String getDescr(Entity mediaType) { + return "RealMedia"; + } + + public String getPublishHost() { + return StringUtil.removeSlash(configuration.getString("Producer.RealMedia.Host")); + } + +} + + + diff --git a/source/mircoders/module/ModuleArticleType.java b/source/mircoders/module/ModuleArticleType.java index 13f4d7f1..9e52a298 100755 --- a/source/mircoders/module/ModuleArticleType.java +++ b/source/mircoders/module/ModuleArticleType.java @@ -29,10 +29,12 @@ */ package mircoders.module; -import mir.log.LoggerWrapper; -import mir.module.*; -import mir.util.*; -import mir.storage.StorageObject; +import mir.log.LoggerWrapper; +import mir.module.AbstractModule; +import mir.module.ModuleExc; +import mir.module.ModuleFailure; +import mir.storage.StorageObject; +import mir.util.JDBCStringRoutines; public class ModuleArticleType extends AbstractModule { static LoggerWrapper logger = new LoggerWrapper("Module.ArticleType"); diff --git a/source/mircoders/module/ModuleComment.java b/source/mircoders/module/ModuleComment.java index 9055e9e6..b936159f 100755 --- a/source/mircoders/module/ModuleComment.java +++ b/source/mircoders/module/ModuleComment.java @@ -18,28 +18,26 @@ * 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 mircoders.module; -import java.util.Map; - -import mir.entity.Entity; -import mir.log.LoggerWrapper; -import mir.module.AbstractModule; -import mir.module.ModuleExc; -import mir.module.ModuleFailure; -import mir.storage.StorageObject; -import mircoders.storage.DatabaseComment; +import java.util.Map; + +import mir.entity.Entity; +import mir.log.LoggerWrapper; +import mir.module.AbstractModule; +import mir.module.ModuleExc; +import mir.module.ModuleFailure; +import mir.storage.StorageObject; import mircoders.storage.DatabaseContent; -import freemarker.template.SimpleList; /* @@ -58,15 +56,6 @@ public class ModuleComment extends AbstractModule this.theStorage = theStorage; } - public SimpleList getCommentAsSimpleList() throws ModuleExc, ModuleFailure { - try { - return ((DatabaseComment)theStorage).getPopupData(); - } - catch (Throwable e) { - throw new ModuleFailure(e); - } - } - public void deleteById (String anId) throws ModuleExc, ModuleFailure { try { Entity theEntity = theStorage.selectById((String)anId); diff --git a/source/mircoders/module/ModuleMediaType.java b/source/mircoders/module/ModuleMediaType.java index 317ff246..b6d5dadb 100755 --- a/source/mircoders/module/ModuleMediaType.java +++ b/source/mircoders/module/ModuleMediaType.java @@ -18,16 +18,16 @@ * 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 mircoders.module; import java.util.List; @@ -72,7 +72,7 @@ public class ModuleMediaType extends AbstractModule { throw new UnsupportedMimeTypeExc("Unsupported mimetype: " + aMimeType, aMimeType); } - return (Entity) mediaTypes.get(0); + return (Entity) mediaTypes.elementAt(0); } public static class MimeTypeExc extends ModuleExc { diff --git a/source/mircoders/module/ModuleMediafolder.java b/source/mircoders/module/ModuleMediafolder.java index 562a8b6c..98b25b1b 100755 --- a/source/mircoders/module/ModuleMediafolder.java +++ b/source/mircoders/module/ModuleMediafolder.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 mircoders.module; @@ -44,15 +44,12 @@ import mir.module.ModuleExc; import mir.module.ModuleFailure; import mir.storage.StorageObject; import mircoders.storage.DatabaseMediafolder; -import freemarker.template.SimpleList; public class ModuleMediafolder extends AbstractModule { static LoggerWrapper logger = new LoggerWrapper("Module.Mediafolder"); -// Kontruktor - public ModuleMediafolder(StorageObject aStorage) { if (aStorage == null) @@ -60,17 +57,4 @@ public class ModuleMediafolder extends AbstractModule theStorage = aStorage; } - -// Methoden - - public SimpleList getPopupData() throws ModuleExc, ModuleFailure { - try { - return ((DatabaseMediafolder)theStorage).getPopupData(); - } - catch (Throwable e) { - throw new ModuleFailure(e); - } - } - - } diff --git a/source/mircoders/module/ModuleTopics.java b/source/mircoders/module/ModuleTopics.java index cd8a7816..d868ab62 100755 --- a/source/mircoders/module/ModuleTopics.java +++ b/source/mircoders/module/ModuleTopics.java @@ -39,14 +39,6 @@ import mir.module.ModuleExc; import mir.module.ModuleFailure; import mir.storage.StorageObject; import mircoders.storage.DatabaseTopics; -import freemarker.template.SimpleList; - -/* - * ThemenModule - - * - * - * @author RK - */ public class ModuleTopics extends AbstractModule { @@ -56,15 +48,6 @@ public class ModuleTopics extends AbstractModule { this.theStorage = theStorage; } - public SimpleList getTopicsAsSimpleList() throws ModuleExc, ModuleFailure { - try { - return ((DatabaseTopics) theStorage).getPopupData(); - } - catch (Throwable e) { - throw new ModuleFailure(e); - } - } - /** * Method getTopicList * diff --git a/source/mircoders/pdf/PDFGenerator.java b/source/mircoders/pdf/PDFGenerator.java index 9487e0cc..b3d5f62c 100755 --- a/source/mircoders/pdf/PDFGenerator.java +++ b/source/mircoders/pdf/PDFGenerator.java @@ -32,6 +32,7 @@ package mircoders.pdf; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.MalformedURLException; +import java.util.*; import com.lowagie.text.BadElementException; import com.lowagie.text.Document; @@ -53,13 +54,13 @@ import gnu.regexp.REMatch; import gnu.regexp.REMatchEnumeration; import mir.config.MirPropertiesConfiguration; -import mir.entity.EntityList; +import mir.entity.*; import mir.log.LoggerWrapper; import mir.misc.StringUtil; import mir.util.DateTimeFunctions; import mircoders.entity.EntityContent; import mircoders.entity.EntityImages; -import mircoders.storage.DatabaseContentToMedia; +import mircoders.storage.*; public class PDFGenerator{ @@ -417,7 +418,7 @@ public class PDFGenerator{ logger.error("runaway description...try increasing the line height or decreasing the font size"); } - public void addArticleContent(ColumnText ct,String theContent,EntityList images){ + public void addArticleContent(ColumnText ct,String theContent,Iterator images){ //let's go ahead and add in all the body text Paragraph contentP=new Paragraph(theContent,new Font(contentFontFamily,contentFontSize)); ct.addText(contentP); @@ -635,7 +636,11 @@ public class PDFGenerator{ * source */ - EntityList images=DatabaseContentToMedia.getInstance().getImages(entityContent); + Iterator images = new EntityBrowser( + DatabaseImages.getInstance(), + "exists (select * from content_x_media where content_id=" + entityContent.getId() + " and media_id=id)", + "id desc", 30, -1, 0); + String isHTML = entityContent.getValue("is_html"); String theTitle = entityContent.getValue("title"); String theCreator = entityContent.getValue("creator"); diff --git a/source/mircoders/producer/ContentModifyingProducerNode.java b/source/mircoders/producer/ContentModifyingProducerNode.java index 61e01559..3f788836 100755 --- a/source/mircoders/producer/ContentModifyingProducerNode.java +++ b/source/mircoders/producer/ContentModifyingProducerNode.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 mircoders.producer; @@ -80,7 +80,7 @@ public class ContentModifyingProducerNode implements ProducerNode { entity.setValueForProperty(fieldName, value); entity.update(); - aLogger.info(" Modified content " + entity.get("id") + ": " + fieldName + " = " + value ); + aLogger.info(" Modified content " + entity.getId() + ": " + fieldName + " = " + value ); } catch (Throwable t) { aLogger.error("Error while modifying content: " + t.getMessage()); diff --git a/source/mircoders/producer/PDFPreFormattingProducerNode.java b/source/mircoders/producer/PDFPreFormattingProducerNode.java index 86ad9a91..77fd4c6d 100755 --- a/source/mircoders/producer/PDFPreFormattingProducerNode.java +++ b/source/mircoders/producer/PDFPreFormattingProducerNode.java @@ -1,230 +1,230 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with any library licensed under the Apache Software License, - * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library - * (or with modified versions of the above that use the same license as the above), - * and distribute linked combinations including the two. You must obey the - * GNU General Public License in all respects for all of the code used other than - * the above mentioned libraries. If you modify this file, you may extend this - * exception to your version of the file, but you are not obligated to do so. - * If you do not wish to do so, delete this exception statement from your version. - */ - -package mircoders.producer; - -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - -import mir.entity.Entity; -import mir.entity.EntityList; -import mir.entity.adapter.EntityAdapter; -import mir.log.LoggerToWriterAdapter; -import mir.log.LoggerWrapper; -import mir.misc.StringUtil; -import mir.producer.ProducerFailure; -import mir.producer.ProducerNode; -import mir.util.CachingRewindableIterator; -import mir.util.HTMLRoutines; -import mir.util.ParameterExpander; -import mircoders.entity.EntityContent; -import mircoders.entity.EntityImages; -import mircoders.storage.DatabaseContentToMedia; - -//because images are returned as a template model!(maybe not needed after all!) -//import freemarker.template.*; - - -public class PDFPreFormattingProducerNode implements ProducerNode { - private String contentKey; - private int numLinesBetweenImages; - private float contentAreaWidthCM; - private float characterWidthCM; - private float pixelWidthCM; - private float lineHeightCM; - - public PDFPreFormattingProducerNode(String aContentKey,String someNumLinesBetweenImages,String aContentAreaWidthCM,String aCharacterWidthCM,String aPixelWidthCM,String aLineHeightCM) { - contentKey = aContentKey; - numLinesBetweenImages=(new Integer(someNumLinesBetweenImages)).intValue(); - contentAreaWidthCM=(new Float(aContentAreaWidthCM)).floatValue(); - characterWidthCM=(new Float(aCharacterWidthCM)).floatValue(); - pixelWidthCM=(new Float(aPixelWidthCM)).floatValue(); - lineHeightCM=(new Float(aLineHeightCM)).floatValue(); - - // float characterWidthCM = 0.17F; - //float contentAreaWidthCM = 16; - //float pixelWidthCM = .03F; - //float lineHeightCM = .5F; - } - - public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure { - Object data; - Entity entity; - - try { - data = ParameterExpander.findValueForKey( aValueMap, contentKey ); - - if (! (data instanceof EntityAdapter)) { - throw new ProducerFailure("PDFPreFormattingProducerNode: value of '"+contentKey+"' is not an EntityAdapter, but an " + data.getClass().getName(), null); - } - - entity = ((EntityAdapter) data).getEntity(); - if (! (entity instanceof EntityContent)) { - throw new ProducerFailure("PDFPreFormattingProducerNode: value of '"+contentKey+"' is not a content EntityAdapter, but a " + entity.getClass().getName() + " adapter", null); - } - - int currentPosition = 0; - - //int numLinesBetweenImages=3; - - - - - int numCharsInAnImagelessRow = (new Float(numLinesBetweenImages * (contentAreaWidthCM/characterWidthCM))).intValue(); - - boolean outOfText = false; - - ArrayList brokenUpContent = new ArrayList(); - - - EntityList images=DatabaseContentToMedia.getInstance().getImages((EntityContent)entity); - String theContent = ((EntityContent) entity).getValue("content_data"); - //remove pesky characters - theContent = HTMLRoutines.encodeXML(theContent); - //put in the
tags so we can turn them to empty blocks - theContent = StringUtil.convertNewline2Break(theContent); - - if (images == null){ - Map row = new HashMap(); - row.put("text",theContent); - row.put("hasImage","0"); - brokenUpContent.add(row); - } - if (images != null){ - //need to add checks for out of content! - Map row0 = new HashMap(); - if (numCharsInAnImagelessRow>(theContent).length()){ - row0.put("text",theContent); - outOfText = true; - } - else { - //break on words so we don't split html entities - int lastSpaceAt = theContent.lastIndexOf(" ",numCharsInAnImagelessRow); - row0.put("text",theContent.substring(0,lastSpaceAt)); - currentPosition=lastSpaceAt; - } - row0.put("hasImage","0"); - brokenUpContent.add(row0); - aLogger.debug("CP1 is "+ currentPosition); - while(images.hasNext()){ - Map row1 = new HashMap(); - Map row2 = new HashMap(); - EntityImages currentImage=(EntityImages) images.next(); - float img_width=(new Float(currentImage.getValue("img_width"))).floatValue(); - float img_height=(new Float(currentImage.getValue("img_height"))).floatValue(); - - //oversize images must be shrunk - if (img_width>250){ - img_height=(new Float((new Float(img_height*(250.0F/img_width))).intValue())).floatValue(); - img_width=250.0F; - } - - - //calculate how much text goes in the column(use 8 pixels to pad the column) - float text_widthCM = contentAreaWidthCM-((img_width+8)*pixelWidthCM); - float number_of_lines = img_height*pixelWidthCM/lineHeightCM; //don't worry we will make it an int - //add one line for image description - int text_amount= (new Float((text_widthCM/characterWidthCM)*(number_of_lines+1))).intValue(); - - row1.put("text_widthCM",Float.toString(text_widthCM)); - - row1.put("img_title",currentImage.getValue("title")); - - row1.put("img_width",Float.toString(img_width)); - row1.put("img_height",Float.toString(img_height)); - - aLogger.debug("img_width " +Float.toString(img_width)); - aLogger.debug("img_height "+Float.toString(img_height)); - - row1.put("img_src",currentImage.getValue("publish_path")); - row1.put("hasImage","1"); - if (! outOfText){ - try { - int lastSpaceAt = theContent.lastIndexOf(" ",currentPosition+text_amount); - row1.put("text",theContent.substring(currentPosition,lastSpaceAt)); - currentPosition=lastSpaceAt; - } - catch (IndexOutOfBoundsException e){ - row1.put("text",theContent.substring(currentPosition)); - outOfText = true; - } - } - aLogger.debug("CP2 is "+ currentPosition); - brokenUpContent.add(row1); - - if (! outOfText){ - try { - int lastSpaceAt = theContent.lastIndexOf(" ",currentPosition+numCharsInAnImagelessRow); - row2.put("text",theContent.substring(currentPosition,lastSpaceAt)); - currentPosition=lastSpaceAt; - } - catch (IndexOutOfBoundsException e){ - row2.put("text",theContent.substring(currentPosition)); - outOfText = true; - } - } - row2.put("hasImage","0"); - brokenUpContent.add(row2); - - aLogger.debug("CP3 is "+ currentPosition); - } - Map row3 = new HashMap(); - if (! outOfText){ - row3.put("text",theContent.substring(currentPosition)); - row3.put("hasImage","0"); - brokenUpContent.add(row3); - } - - } - - - - - - ParameterExpander.setValueForKey( - aValueMap, - "data.formatted_content", - new CachingRewindableIterator(brokenUpContent.iterator()) - ); - - - } - catch (Throwable t) { - aLogger.error("Error while formatting content for PDF: " + t.getMessage()); - t.printStackTrace(new PrintWriter(new LoggerToWriterAdapter(aLogger, LoggerWrapper.DEBUG_MESSAGE))); - } - } -} - - - - +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, but you are not obligated to do so. + * If you do not wish to do so, delete this exception statement from your version. + */ + +package mircoders.producer; + +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.*; + +import mir.entity.*; +import mir.entity.EntityList; +import mir.entity.adapter.EntityAdapter; +import mir.log.LoggerToWriterAdapter; +import mir.log.LoggerWrapper; +import mir.misc.StringUtil; +import mir.producer.ProducerFailure; +import mir.producer.ProducerNode; +import mir.util.CachingRewindableIterator; +import mir.util.HTMLRoutines; +import mir.util.ParameterExpander; +import mircoders.entity.EntityContent; +import mircoders.entity.EntityImages; +import mircoders.storage.*; + + +public class PDFPreFormattingProducerNode implements ProducerNode { + private String contentKey; + private int numLinesBetweenImages; + private float contentAreaWidthCM; + private float characterWidthCM; + private float pixelWidthCM; + private float lineHeightCM; + + public PDFPreFormattingProducerNode(String aContentKey,String someNumLinesBetweenImages,String aContentAreaWidthCM,String aCharacterWidthCM,String aPixelWidthCM,String aLineHeightCM) { + contentKey = aContentKey; + numLinesBetweenImages=(new Integer(someNumLinesBetweenImages)).intValue(); + contentAreaWidthCM=(new Float(aContentAreaWidthCM)).floatValue(); + characterWidthCM=(new Float(aCharacterWidthCM)).floatValue(); + pixelWidthCM=(new Float(aPixelWidthCM)).floatValue(); + lineHeightCM=(new Float(aLineHeightCM)).floatValue(); + + // float characterWidthCM = 0.17F; + //float contentAreaWidthCM = 16; + //float pixelWidthCM = .03F; + //float lineHeightCM = .5F; + } + + public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure { + Object data; + Entity entity; + + try { + data = ParameterExpander.findValueForKey( aValueMap, contentKey ); + + if (! (data instanceof EntityAdapter)) { + throw new ProducerFailure("PDFPreFormattingProducerNode: value of '"+contentKey+"' is not an EntityAdapter, but an " + data.getClass().getName(), null); + } + + entity = ((EntityAdapter) data).getEntity(); + if (! (entity instanceof EntityContent)) { + throw new ProducerFailure("PDFPreFormattingProducerNode: value of '"+contentKey+"' is not a content EntityAdapter, but a " + entity.getClass().getName() + " adapter", null); + } + + int currentPosition = 0; + + //int numLinesBetweenImages=3; + + + + + int numCharsInAnImagelessRow = (new Float(numLinesBetweenImages * (contentAreaWidthCM/characterWidthCM))).intValue(); + + boolean outOfText = false; + + ArrayList brokenUpContent = new ArrayList(); + + Iterator images = new EntityBrowser( + DatabaseImages.getInstance(), + "exists (select * from content_x_media where content_id=" + entity.getId() + " and media_id=id)", + "id desc", 30, -1, 0); + + String theContent = ((EntityContent) entity).getValue("content_data"); + //remove pesky characters + theContent = HTMLRoutines.encodeXML(theContent); + //put in the
tags so we can turn them to empty blocks + theContent = StringUtil.convertNewline2Break(theContent); + + if (images == null){ + Map row = new HashMap(); + row.put("text",theContent); + row.put("hasImage","0"); + brokenUpContent.add(row); + } + if (images != null){ + //need to add checks for out of content! + Map row0 = new HashMap(); + if (numCharsInAnImagelessRow>(theContent).length()){ + row0.put("text",theContent); + outOfText = true; + } + else { + //break on words so we don't split html entities + int lastSpaceAt = theContent.lastIndexOf(" ",numCharsInAnImagelessRow); + row0.put("text",theContent.substring(0,lastSpaceAt)); + currentPosition=lastSpaceAt; + } + row0.put("hasImage","0"); + brokenUpContent.add(row0); + aLogger.debug("CP1 is "+ currentPosition); + while(images.hasNext()){ + Map row1 = new HashMap(); + Map row2 = new HashMap(); + EntityImages currentImage=(EntityImages) images.next(); + float img_width=(new Float(currentImage.getValue("img_width"))).floatValue(); + float img_height=(new Float(currentImage.getValue("img_height"))).floatValue(); + + //oversize images must be shrunk + if (img_width>250){ + img_height=(new Float((new Float(img_height*(250.0F/img_width))).intValue())).floatValue(); + img_width=250.0F; + } + + + //calculate how much text goes in the column(use 8 pixels to pad the column) + float text_widthCM = contentAreaWidthCM-((img_width+8)*pixelWidthCM); + float number_of_lines = img_height*pixelWidthCM/lineHeightCM; //don't worry we will make it an int + //add one line for image description + int text_amount= (new Float((text_widthCM/characterWidthCM)*(number_of_lines+1))).intValue(); + + row1.put("text_widthCM",Float.toString(text_widthCM)); + + row1.put("img_title",currentImage.getValue("title")); + + row1.put("img_width",Float.toString(img_width)); + row1.put("img_height",Float.toString(img_height)); + + aLogger.debug("img_width " +Float.toString(img_width)); + aLogger.debug("img_height "+Float.toString(img_height)); + + row1.put("img_src",currentImage.getValue("publish_path")); + row1.put("hasImage","1"); + if (! outOfText){ + try { + int lastSpaceAt = theContent.lastIndexOf(" ",currentPosition+text_amount); + row1.put("text",theContent.substring(currentPosition,lastSpaceAt)); + currentPosition=lastSpaceAt; + } + catch (IndexOutOfBoundsException e){ + row1.put("text",theContent.substring(currentPosition)); + outOfText = true; + } + } + aLogger.debug("CP2 is "+ currentPosition); + brokenUpContent.add(row1); + + if (! outOfText){ + try { + int lastSpaceAt = theContent.lastIndexOf(" ",currentPosition+numCharsInAnImagelessRow); + row2.put("text",theContent.substring(currentPosition,lastSpaceAt)); + currentPosition=lastSpaceAt; + } + catch (IndexOutOfBoundsException e){ + row2.put("text",theContent.substring(currentPosition)); + outOfText = true; + } + } + row2.put("hasImage","0"); + brokenUpContent.add(row2); + + aLogger.debug("CP3 is "+ currentPosition); + } + Map row3 = new HashMap(); + if (! outOfText){ + row3.put("text",theContent.substring(currentPosition)); + row3.put("hasImage","0"); + brokenUpContent.add(row3); + } + + } + + + + + + ParameterExpander.setValueForKey( + aValueMap, + "data.formatted_content", + new CachingRewindableIterator(brokenUpContent.iterator()) + ); + + + } + catch (Throwable t) { + aLogger.error("Error while formatting content for PDF: " + t.getMessage()); + t.printStackTrace(new PrintWriter(new LoggerToWriterAdapter(aLogger, LoggerWrapper.DEBUG_MESSAGE))); + } + } +} + + + + diff --git a/source/mircoders/servlet/ServletHelper.java b/source/mircoders/servlet/ServletHelper.java index 11e23759..5ed322ca 100755 --- a/source/mircoders/servlet/ServletHelper.java +++ b/source/mircoders/servlet/ServletHelper.java @@ -1,173 +1,185 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with any library licensed under the Apache Software License, - * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library - * (or with modified versions of the above that use the same license as the above), - * and distribute linked combinations including the two. You must obey the - * GNU General Public License in all respects for all of the code used other than - * the above mentioned libraries. If you modify this file, you may extend this - * exception to your version of the file, but you are not obligated to do so. - * If you do not wish to do so, delete this exception statement from your version. - */ -package mircoders.servlet; - -import java.io.PrintWriter; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.struts.util.MessageResources; - -import mir.config.MirPropertiesConfiguration; -import mir.entity.adapter.EntityIteratorAdapter; -import mir.generator.Generator; -import mir.log.LoggerWrapper; -import mir.servlet.ServletModuleExc; -import mir.servlet.ServletModuleFailure; -import mir.util.CachingRewindableIterator; -import mir.util.ResourceBundleGeneratorFunction; -import mircoders.entity.EntityUsers; -import mircoders.global.MirGlobal; - - -public class ServletHelper { - static LoggerWrapper logger = new LoggerWrapper("ServletModule.Helper"); - - - public static Map makeGenerationData(HttpServletRequest aRequest, HttpServletResponse aResponse, Locale[] aLocales) throws ServletModuleExc { - return makeGenerationData(aRequest, aResponse, aLocales, "bundles.adminlocal", "bundles.admin"); - } - - public static Map makeGenerationData(HttpServletRequest aRequest, HttpServletResponse aResponse, Locale[] aLocales, String aBundle) throws ServletModuleExc { - return makeGenerationData(aRequest, aResponse, aLocales, aBundle, aBundle); - } - - public static Map makeGenerationData(HttpServletRequest aRequest, HttpServletResponse aResponse, Locale[] aLocales, String aBundle, String aDefaultBundle) throws ServletModuleExc { - - try { - Map result = new HashMap(); - - MirGlobal.localizer().producerAssistant().initializeGenerationValueSet(result); - - // ML: hackish - ((Map) result.get("config")).put("actionRoot", - aResponse.encodeURL(MirGlobal.config().getString("RootUri") + "/servlet/Mir")); - - result.put("returnurl", null); - result.put("login_user", getUser(aRequest)); - - 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); - - result.put( "lang", - new ResourceBundleGeneratorFunction( aLocales, - new MessageResources[] { MessageResources.getMessageResources(aBundle), - MessageResources.getMessageResources(aDefaultBundle)})); - - return result; - } - catch (Throwable t) { - throw new ServletModuleFailure(t); - } - } - - public static void generateResponse(PrintWriter aWriter, Map aGenerationData, String aGenerator) throws ServletModuleExc { - Generator generator; - - try { - generator = MirGlobal.localizer().generators().makeAdminGeneratorLibrary().makeGenerator(aGenerator); - - generator.generate(aWriter, aGenerationData, logger); - } - catch (Throwable t) { - throw new ServletModuleFailure(t); - } - } - - public static void generateOpenPostingResponse(PrintWriter aWriter, Map aGenerationData, String aGenerator) throws ServletModuleExc { - Generator generator; - - try { - generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator); - - generator.generate(aWriter, aGenerationData, logger); - } - catch (Throwable t) { - throw new ServletModuleFailure(t); - } - } - - public static void redirect(HttpServletResponse aResponse, String aQuery) throws ServletModuleExc, ServletModuleFailure { - try { - aResponse.sendRedirect(aResponse.encodeRedirectURL(MirPropertiesConfiguration.instance().getString("RootUri") + "/servlet/Mir?"+aQuery)); - } - catch (Throwable t) { - throw new ServletModuleFailure("ServletModule.redirect: " +t.getMessage(), t); - } - } - - public static void redirect(HttpServletResponse aResponse, String aModule, String aMethod) throws ServletModuleExc, ServletModuleFailure { - redirect(aResponse, "module="+aModule+"&do="+aMethod); - } - - public static void setUser(HttpServletRequest aRequest, EntityUsers aUser) { - if (aUser!=null) - aRequest.getSession().setAttribute("login.uid", aUser); - else - aRequest.getSession().removeAttribute("login.uid"); - } - - public static EntityUsers getUser(HttpServletRequest aRequest) { - return (EntityUsers) aRequest.getSession().getAttribute("login.uid"); - } - public static String getUserName(HttpServletRequest aRequest) { - EntityUsers user = getUser(aRequest); - - if (user!=null) - return user.getValue("login"); - else - return "nobody"; - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, but you are not obligated to do so. + * If you do not wish to do so, delete this exception statement from your version. + */ +package mircoders.servlet; + +import java.io.PrintWriter; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.struts.util.MessageResources; + +import mir.config.MirPropertiesConfiguration; +import mir.entity.adapter.*; +import mir.generator.Generator; +import mir.log.LoggerWrapper; +import mir.servlet.ServletModuleExc; +import mir.servlet.ServletModuleFailure; +import mir.util.CachingRewindableIterator; +import mir.util.ResourceBundleGeneratorFunction; +import mircoders.entity.EntityUsers; +import mircoders.global.MirGlobal; + + +public class ServletHelper { + static LoggerWrapper logger = new LoggerWrapper("ServletModule.Helper"); + + + public static Map makeGenerationData(HttpServletRequest aRequest, HttpServletResponse aResponse, Locale[] aLocales) throws ServletModuleExc { + return makeGenerationData(aRequest, aResponse, aLocales, "bundles.adminlocal", "bundles.admin"); + } + + public static Map makeGenerationData(HttpServletRequest aRequest, HttpServletResponse aResponse, Locale[] aLocales, String aBundle) throws ServletModuleExc { + return makeGenerationData(aRequest, aResponse, aLocales, aBundle, aBundle); + } + + public static Map makeGenerationData(HttpServletRequest aRequest, HttpServletResponse aResponse, Locale[] aLocales, String aBundle, String aDefaultBundle) throws ServletModuleExc { + + try { + Map result = new HashMap(); + + MirGlobal.localizer().producerAssistant().initializeGenerationValueSet(result); + + // ML: hackish + ((Map) result.get("config")).put("actionRoot", + aResponse.encodeURL(MirGlobal.config().getString("RootUri") + "/servlet/Mir")); + + result.put("returnurl", null); + result.put("login_user", getUserAdapter(aRequest)); + + 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); + + result.put( "lang", + new ResourceBundleGeneratorFunction( aLocales, + new MessageResources[] { MessageResources.getMessageResources(aBundle), + MessageResources.getMessageResources(aDefaultBundle)})); + + return result; + } + catch (Throwable t) { + throw new ServletModuleFailure(t); + } + } + + public static void generateResponse(PrintWriter aWriter, Map aGenerationData, String aGenerator) throws ServletModuleExc { + logger.debug("generator used: " + aGenerator); + + Generator generator; + + try { + generator = MirGlobal.localizer().generators().makeAdminGeneratorLibrary().makeGenerator(aGenerator); + + generator.generate(aWriter, aGenerationData, logger); + } + catch (Throwable t) { + throw new ServletModuleFailure(t); + } + } + + public static void generateOpenPostingResponse(PrintWriter aWriter, Map aGenerationData, String aGenerator) throws ServletModuleExc { + Generator generator; + + try { + generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator); + + generator.generate(aWriter, aGenerationData, logger); + } + catch (Throwable t) { + throw new ServletModuleFailure(t); + } + } + + public static void redirect(HttpServletResponse aResponse, String aQuery) throws ServletModuleExc, ServletModuleFailure { + try { + aResponse.sendRedirect(aResponse.encodeRedirectURL(MirPropertiesConfiguration.instance().getString("RootUri") + "/servlet/Mir?"+aQuery)); + } + catch (Throwable t) { + throw new ServletModuleFailure("ServletModule.redirect: " +t.getMessage(), t); + } + } + + public static void redirect(HttpServletResponse aResponse, String aModule, String aMethod) throws ServletModuleExc, ServletModuleFailure { + redirect(aResponse, "module="+aModule+"&do="+aMethod); + } + + public static void setUser(HttpServletRequest aRequest, EntityUsers aUser) { + if (aUser!=null) + aRequest.getSession().setAttribute("login.uid", aUser); + else + aRequest.getSession().removeAttribute("login.uid"); + } + + public static EntityUsers getUser(HttpServletRequest aRequest) { + return (EntityUsers) aRequest.getSession().getAttribute("login.uid"); + } + + public static EntityAdapter getUserAdapter(HttpServletRequest aRequest) { + try { + return MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter( "user", (EntityUsers) aRequest.getSession().getAttribute("login.uid")); + } + catch (Throwable t) { + throw new ServletModuleFailure (t); + } + } + + public static String getUserName(HttpServletRequest aRequest) { + EntityUsers user = getUser(aRequest); + + if (user!=null) + return user.getValue("login"); + else + return "nobody"; + } +} diff --git a/source/mircoders/servlet/ServletModuleAdmin.java b/source/mircoders/servlet/ServletModuleAdmin.java index f7534b66..ec85a080 100755 --- a/source/mircoders/servlet/ServletModuleAdmin.java +++ b/source/mircoders/servlet/ServletModuleAdmin.java @@ -1,70 +1,102 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with any library licensed under the Apache Software License, - * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library - * (or with modified versions of the above that use the same license as the above), - * and distribute linked combinations including the two. You must obey the - * GNU General Public License in all respects for all of the code used other than - * the above mentioned libraries. If you modify this file, you may extend this - * exception to your version of the file, but you are not obligated to do so. - * If you do not wish to do so, delete this exception statement from your version. - */ -package mircoders.servlet; - -import java.util.Locale; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import mir.log.LoggerWrapper; -import mir.servlet.ServletModule; -import mir.servlet.ServletModuleFailure; -import mir.util.URLBuilder; - -public class ServletModuleAdmin extends ServletModule -{ - private static ServletModuleAdmin instance = new ServletModuleAdmin(); - public static ServletModule getInstance() { return instance; } - - private ServletModuleAdmin() { - logger = new LoggerWrapper("ServletModule.Admin"); - defaultAction = "showSuperUserMenu"; - } - - public void superusermenu(HttpServletRequest aRequest, HttpServletResponse aResponse) { - URLBuilder urlBuilder = new URLBuilder(); - int count; - - try { - Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}); - urlBuilder.setValue("module", "Admin"); - urlBuilder.setValue("do", "superusermenu"); - - responseData.put("thisurl" , urlBuilder.getQuery()); - - ServletHelper.generateResponse(aResponse.getWriter(), responseData, "superusermenu.template"); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, but you are not obligated to do so. + * If you do not wish to do so, delete this exception statement from your version. + */ +package mircoders.servlet; + +import java.util.Locale; +import java.util.Map; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import mir.entity.adapter.EntityIteratorAdapter; +import mir.log.LoggerWrapper; +import mir.servlet.ServletModule; +import mir.servlet.ServletModuleFailure; +import mir.util.CachingRewindableIterator; +import mir.util.URLBuilder; +import mircoders.global.MirGlobal; + +public class ServletModuleAdmin extends ServletModule +{ + private static ServletModuleAdmin instance = new ServletModuleAdmin(); + public static ServletModule getInstance() { return instance; } + + private ServletModuleAdmin() { + logger = new LoggerWrapper("ServletModule.Admin"); + defaultAction = "start"; + } + + public void superusermenu(HttpServletRequest aRequest, HttpServletResponse aResponse) { + URLBuilder urlBuilder = new URLBuilder(); + int count; + + try { + Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}); + urlBuilder.setValue("module", "Admin"); + urlBuilder.setValue("do", "superusermenu"); + + responseData.put("thisurl" , urlBuilder.getQuery()); + + ServletHelper.generateResponse(aResponse.getWriter(), responseData, "superusermenu.template"); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + public void start(HttpServletRequest aRequest, HttpServletResponse aResponse) { + String startTemplate = configuration.getString("Mir.StartTemplate"); + String sessionUrl = aResponse.encodeURL(""); + + try { + Map mergeData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)} + , "bundles.admin", "bundles.adminlocal"); + mergeData.put("messages", + new CachingRewindableIterator( + new EntityIteratorAdapter("", "webdb_create desc", 10, + MirGlobal.localizer().dataModel().adapterModel(), "internalMessage", 10, 0))); + + mergeData.put("fileeditentries", ( (ServletModuleFileEdit) ServletModuleFileEdit.getInstance()).getEntries()); + mergeData.put("administeroperations", ( (ServletModuleLocalizer) ServletModuleLocalizer.getInstance()).getAdministerOperations()); + + mergeData.put("searchvalue", null); + mergeData.put("searchfield", null); + mergeData.put("searchispublished", null); + mergeData.put("searcharticletype", null); + mergeData.put("searchorder", null); + mergeData.put("selectarticleurl", null); + + ServletHelper.generateResponse(aResponse.getWriter(), mergeData, startTemplate); + } + catch (Exception e) { + throw new ServletModuleFailure(e); + } + } + +} diff --git a/source/mircoders/servlet/ServletModuleArticleType.java b/source/mircoders/servlet/ServletModuleArticleType.java index 826d4f80..63de8b3c 100755 --- a/source/mircoders/servlet/ServletModuleArticleType.java +++ b/source/mircoders/servlet/ServletModuleArticleType.java @@ -1,56 +1,64 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with any library licensed under the Apache Software License, - * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library - * (or with modified versions of the above that use the same license as the above), - * and distribute linked combinations including the two. You must obey the - * GNU General Public License in all respects for all of the code used other than - * the above mentioned libraries. If you modify this file, you may extend this - * exception to your version of the file, but you are not obligated to do so. - * If you do not wish to do so, delete this exception statement from your version. - */ -package mircoders.servlet; - -import mir.config.MirPropertiesConfiguration; -import mir.log.LoggerWrapper; -import mir.servlet.ServletModule; -import mircoders.module.ModuleArticleType; -import mircoders.storage.DatabaseArticleType; - -public class ServletModuleArticleType extends ServletModule -{ - private static ServletModuleArticleType instance = new ServletModuleArticleType(); - public static ServletModule getInstance() { return instance; } - - private ServletModuleArticleType() { - logger = new LoggerWrapper("ServletModule.ArticleType"); - try { - configuration = MirPropertiesConfiguration.instance(); - templateListString = configuration.getString("ServletModule.ArticleType.ListTemplate"); - templateObjektString = configuration.getString("ServletModule.ArticleType.EditTemplate"); - templateConfirmString = configuration.getString("ServletModule.ArticleType.ConfirmTemplate"); - mainModule = new ModuleArticleType(DatabaseArticleType.getInstance()); - } - catch (Exception e) { - logger.error("Initialization of ServletModuleArticleType failed!: " + e.getMessage()); - } - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, but you are not obligated to do so. + * If you do not wish to do so, delete this exception statement from your version. + */ +package mircoders.servlet; + +import mir.log.LoggerWrapper; +import mir.servlet.ServletModule; +import mircoders.global.MirGlobal; +import mircoders.module.ModuleArticleType; +import mircoders.storage.DatabaseArticleType; + +/** + * + *

Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ +public class ServletModuleArticleType extends ServletModule +{ + private static ServletModuleArticleType instance = new ServletModuleArticleType(); + public static ServletModule getInstance() { return instance; } + + private ServletModuleArticleType() { + logger = new LoggerWrapper("ServletModule.ArticleType"); + + try { + model = MirGlobal.localizer().dataModel().adapterModel(); + definition = "articleType"; + mainModule = new ModuleArticleType(DatabaseArticleType.getInstance()); + } + catch (Exception e) { + logger.error("Initialization of ServletModuleArticleType failed!: " + e.getMessage()); + } + } +} diff --git a/source/mircoders/servlet/ServletModuleAudio.java b/source/mircoders/servlet/ServletModuleAudio.java index 43262adf..a35f1772 100755 --- a/source/mircoders/servlet/ServletModuleAudio.java +++ b/source/mircoders/servlet/ServletModuleAudio.java @@ -34,6 +34,7 @@ import mir.log.LoggerWrapper; import mir.servlet.ServletModule; import mircoders.module.ModuleUploadedMedia; import mircoders.storage.DatabaseAudio; +import mircoders.global.*; /* * @@ -42,10 +43,6 @@ import mircoders.storage.DatabaseAudio; */ public class ServletModuleAudio extends ServletModuleUploadedMedia { - - //private static DatabaseRights dbRights; - - // Singelton / Contructor private static ServletModuleAudio instance = new ServletModuleAudio(); public static ServletModule getInstance() { @@ -55,18 +52,14 @@ public class ServletModuleAudio extends ServletModuleUploadedMedia { private ServletModuleAudio() { logger = new LoggerWrapper("ServletModule.Audio"); - entityName = "audio"; moduleName = "Audio"; try { - configuration = MirPropertiesConfiguration.instance(); - templateListString = configuration.getString("ServletModule.Audio.ListTemplate"); - templateObjektString = configuration.getString("ServletModule.Audio.ObjektTemplate"); - templateConfirmString = configuration.getString("ServletModule.Audio.ConfirmTemplate"); + model = MirGlobal.localizer().dataModel().adapterModel(); + definition = "audio"; mainModule = new ModuleUploadedMedia(DatabaseAudio.getInstance()); - //dbRights = DatabaseRights.getInstance(); } - catch (Exception e) { + catch (Throwable e) { logger.error("servletmodule audio could not be initialized: " + e.getMessage()); } } diff --git a/source/mircoders/servlet/ServletModuleBreaking.java b/source/mircoders/servlet/ServletModuleBreaking.java index 536d6dac..ca659814 100755 --- a/source/mircoders/servlet/ServletModuleBreaking.java +++ b/source/mircoders/servlet/ServletModuleBreaking.java @@ -1,110 +1,66 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with any library licensed under the Apache Software License, - * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library - * (or with modified versions of the above that use the same license as the above), - * and distribute linked combinations including the two. You must obey the - * GNU General Public License in all respects for all of the code used other than - * the above mentioned libraries. If you modify this file, you may extend this - * exception to your version of the file, but you are not obligated to do so. - * If you do not wish to do so, delete this exception statement from your version. - */ - -package mircoders.servlet; - -import java.net.URLEncoder; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import mir.config.MirPropertiesConfiguration; -import mir.entity.EntityList; -import mir.log.LoggerWrapper; -import mir.misc.HTMLTemplateProcessor; -import mir.servlet.ServletModule; -import mir.servlet.ServletModuleFailure; -import mircoders.module.ModuleBreaking; -import mircoders.storage.DatabaseBreaking; -import freemarker.template.SimpleHash; - -/* - * ServletModuleBreaking - - * Authentified Navigation for Breaking News - * - * - */ - -public class ServletModuleBreaking extends ServletModule -{ - -// Singelton / Kontruktor - - private static ServletModuleBreaking instance = new ServletModuleBreaking(); - public static ServletModule getInstance() { return instance; } - - private ServletModuleBreaking() { - logger = new LoggerWrapper("ServletModule.Breaking"); - try { - configuration = MirPropertiesConfiguration.instance(); - - templateListString = configuration.getString("ServletModule.Breaking.ListTemplate"); - templateObjektString = configuration.getString("ServletModule.Breaking.ObjektTemplate"); - templateConfirmString = configuration.getString("ServletModule.Breaking.ConfirmTemplate"); - - DatabaseBreaking dbb = DatabaseBreaking.getInstance(); - mainModule = new ModuleBreaking(dbb); - } - catch (Exception e) { - logger.error("Initialisation of ServletModuleBreaking failed!: " + e.getMessage()); - } - } - - public void list(HttpServletRequest req, HttpServletResponse res) - { - logger.debug("-- breaking: list"); -// fetch and deliver - try { - SimpleHash mergeData = new SimpleHash(); - String offset = req.getParameter("offset"); - if (offset==null || offset.equals("")) offset="0"; - mergeData.put("offset",offset); - EntityList theList = mainModule.getByWhereClause(null, "webdb_create desc", (new Integer(offset)).intValue()); - mergeData.put("contentlist",theList); - if(theList.getOrder()!=null) { - mergeData.put("order", theList.getOrder()); - mergeData.put("order_encoded", URLEncoder.encode(theList.getOrder())); - } - mergeData.put("count", (new Integer(theList.getCount())).toString()); - mergeData.put("from", (new Integer(theList.getFrom())).toString()); - mergeData.put("to", (new Integer(theList.getTo())).toString()); - if (theList.hasNextBatch()) - mergeData.put("next", (new Integer(theList.getNextBatch())).toString()); - if (theList.hasPrevBatch()) - mergeData.put("prev", (new Integer(theList.getPrevBatch())).toString()); - -// raus damit - HTMLTemplateProcessor.process(res, templateListString, mergeData, res.getWriter(), getLocale(req), getFallbackLocale(req)); - } - catch (Exception e) { - throw new ServletModuleFailure(e); - } - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, but you are not obligated to do so. + * If you do not wish to do so, delete this exception statement from your version. + */ + +package mircoders.servlet; + +import mir.log.LoggerWrapper; +import mir.servlet.ServletModule; +import mircoders.global.MirGlobal; +import mircoders.module.ModuleBreaking; +import mircoders.storage.DatabaseBreaking; + +/** + * + *

Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ + +public class ServletModuleBreaking extends ServletModule +{ + private static ServletModuleBreaking instance = new ServletModuleBreaking(); + public static ServletModule getInstance() { return instance; } + + private ServletModuleBreaking() { + logger = new LoggerWrapper("ServletModule.Breaking"); + + try { + model = MirGlobal.localizer().dataModel().adapterModel(); + definition = "breakingNews"; + mainModule = new ModuleBreaking(DatabaseBreaking.getInstance()); + } + catch (Exception e) { + logger.error("Initialisation of ServletModuleBreaking failed!: " + e.getMessage()); + } + } +} diff --git a/source/mircoders/servlet/ServletModuleComment.java b/source/mircoders/servlet/ServletModuleComment.java index 2c74318b..251c37cb 100755 --- a/source/mircoders/servlet/ServletModuleComment.java +++ b/source/mircoders/servlet/ServletModuleComment.java @@ -75,11 +75,6 @@ public class ServletModuleComment extends ServletModule private ServletModuleComment() { logger = new LoggerWrapper("ServletModule.Comment"); try { - configuration = MirPropertiesConfiguration.instance(); - templateListString = configuration.getString("ServletModule.Comment.ListTemplate"); - templateObjektString = configuration.getString("ServletModule.Comment.ObjektTemplate"); - templateConfirmString = configuration.getString("ServletModule.Comment.ConfirmTemplate"); - mainModule = new ModuleComment(DatabaseComment.getInstance()); moduleContent = new ModuleContent(DatabaseContent.getInstance()); } @@ -140,7 +135,7 @@ public class ServletModuleComment extends ServletModule responseData.put("returnurl", requestParser.getParameter("returnurl")); responseData.put("thisurl", urlBuilder.getQuery()); - ServletHelper.generateResponse(aResponse.getWriter(), responseData, templateObjektString); + ServletHelper.generateResponse(aResponse.getWriter(), responseData, editGenerator); } catch (Throwable e) { throw new ServletModuleFailure(e); @@ -261,7 +256,6 @@ public class ServletModuleComment extends ServletModule HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); URLBuilder urlBuilder = new URLBuilder(); EntityAdapterModel model; - int nrCommentsPerPage = 20; int count; try { @@ -270,8 +264,8 @@ public class ServletModuleComment extends ServletModule Object commentList = new CachingRewindableIterator( - new EntityIteratorAdapter( aWhereClause, anOrderByClause, nrCommentsPerPage, - MirGlobal.localizer().dataModel().adapterModel(), "comment", nrCommentsPerPage, anOffset) + new EntityIteratorAdapter( aWhereClause, anOrderByClause, nrEntitiesPerListPage, + MirGlobal.localizer().dataModel().adapterModel(), "comment", nrEntitiesPerListPage, anOffset) ); responseData.put("nexturl", null); @@ -300,22 +294,22 @@ public class ServletModuleComment extends ServletModule responseData.put("offset" , new Integer(anOffset).toString()); responseData.put("thisurl" , urlBuilder.getQuery()); - if (count>=anOffset+nrCommentsPerPage) { - urlBuilder.setValue("offset", anOffset + nrCommentsPerPage); + if (count>=anOffset+nrEntitiesPerListPage) { + urlBuilder.setValue("offset", anOffset + nrEntitiesPerListPage); responseData.put("nexturl" , urlBuilder.getQuery()); } if (anOffset>0) { - urlBuilder.setValue("offset", Math.max(anOffset - nrCommentsPerPage, 0)); + urlBuilder.setValue("offset", Math.max(anOffset - nrEntitiesPerListPage, 0)); responseData.put("prevurl" , urlBuilder.getQuery()); } responseData.put("comments", commentList); responseData.put("from" , Integer.toString(anOffset+1)); responseData.put("count", Integer.toString(count)); - responseData.put("to", Integer.toString(Math.min(anOffset+nrCommentsPerPage, count))); + responseData.put("to", Integer.toString(Math.min(anOffset+nrEntitiesPerListPage, count))); - ServletHelper.generateResponse(aResponse.getWriter(), responseData, "commentlist.template"); + ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator); } catch (Throwable e) { throw new ServletModuleFailure(e); diff --git a/source/mircoders/servlet/ServletModuleCommentStatus.java b/source/mircoders/servlet/ServletModuleCommentStatus.java index 2f13787e..7696feea 100755 --- a/source/mircoders/servlet/ServletModuleCommentStatus.java +++ b/source/mircoders/servlet/ServletModuleCommentStatus.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 mircoders.servlet; @@ -34,6 +34,8 @@ import mir.log.LoggerWrapper; import mir.servlet.ServletModule; import mircoders.module.ModuleCommentStatus; import mircoders.storage.DatabaseCommentStatus; +import mircoders.global.*; + public class ServletModuleCommentStatus extends ServletModule { @@ -44,13 +46,11 @@ public class ServletModuleCommentStatus extends ServletModule logger = new LoggerWrapper("ServletModule.CommentStatus"); try { - configuration = MirPropertiesConfiguration.instance(); - templateListString = configuration.getString("ServletModule.CommentStatus.ListTemplate"); - templateObjektString = configuration.getString("ServletModule.CommentStatus.EditTemplate"); - templateConfirmString = configuration.getString("ServletModule.CommentStatus.ConfirmTemplate"); - + model = MirGlobal.localizer().dataModel().adapterModel(); + definition = "commentStatus"; mainModule = new ModuleCommentStatus(DatabaseCommentStatus.getInstance()); - } catch (Exception e) { + } + catch (Throwable e) { logger.error("Initialization of ServletModuleCommentStatus failed!: " + e.getMessage()); } } diff --git a/source/mircoders/servlet/ServletModuleContent.java b/source/mircoders/servlet/ServletModuleContent.java index 4f423d4a..87506c0a 100755 --- a/source/mircoders/servlet/ServletModuleContent.java +++ b/source/mircoders/servlet/ServletModuleContent.java @@ -36,15 +36,8 @@ import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.apache.lucene.index.IndexReader; - -import freemarker.template.SimpleHash; - import mir.entity.adapter.EntityAdapterModel; import mir.entity.adapter.EntityIteratorAdapter; @@ -58,44 +51,32 @@ import mir.util.HTTPRequestParser; import mir.util.JDBCStringRoutines; import mir.util.SQLQueryBuilder; import mir.util.URLBuilder; - -import mircoders.global.*; import mircoders.entity.EntityContent; -import mircoders.entity.EntityUsers; import mircoders.global.MirGlobal; import mircoders.module.ModuleContent; -import mircoders.search.IndexUtil; -import mircoders.storage.DatabaseComment; import mircoders.storage.DatabaseContent; -import mircoders.storage.DatabaseContentToMedia; import mircoders.storage.DatabaseContentToTopics; /* * ServletModuleContent - * deliver html for the article admin form. * - * @version $Id: ServletModuleContent.java,v 1.52.2.5 2003/08/13 02:43:56 zapata Exp $ + * @version $Id: ServletModuleContent.java,v 1.52.2.6 2003/09/03 17:49:40 zapata Exp $ * @author rk, mir-coders * */ public class ServletModuleContent extends ServletModule { - private String editTemplate = configuration.getString("ServletModule.Content.ObjektTemplate");; - private String listTemplate = configuration.getString("ServletModule.Content.ListTemplate"); - private static ServletModuleContent instance = new ServletModuleContent(); public static ServletModule getInstance() { return instance; } private ServletModuleContent() { super(); - logger = new LoggerWrapper("ServletModule.Content"); - try { - templateListString = configuration.getString("ServletModule.Content.ListTemplate"); - templateObjektString = configuration.getString("ServletModule.Content.ObjektTemplate"); - templateConfirmString = configuration.getString("ServletModule.Content.ConfirmTemplate"); + logger = new LoggerWrapper("ServletModule.Content"); + try { mainModule = new ModuleContent(DatabaseContent.getInstance()); } catch (Throwable e) { @@ -282,7 +263,7 @@ public class ServletModuleContent extends ServletModule String id = mainModule.set(withValues); DatabaseContentToTopics.getInstance().setTopics(aRequest.getParameter("id"), aRequest.getParameterValues("to_topic")); - if (returnUrl!=null){ + if (returnUrl!=null && !returnUrl.equals("")){ redirect(aResponse, returnUrl); } else @@ -345,7 +326,7 @@ public class ServletModuleContent extends ServletModule responseData.put("returnurl", requestParser.getParameter("returnurl")); responseData.put("thisurl", urlBuilder.getQuery()); - ServletHelper.generateResponse(aResponse.getWriter(), responseData, editTemplate); + ServletHelper.generateResponse(aResponse.getWriter(), responseData, editGenerator); } catch (Throwable e) { throw new ServletModuleFailure(e); @@ -363,7 +344,6 @@ public class ServletModuleContent extends ServletModule HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); URLBuilder urlBuilder = new URLBuilder(); EntityAdapterModel model; - int nrArticlesPerPage = 20; int count; try { @@ -372,8 +352,8 @@ public class ServletModuleContent extends ServletModule Object articleList = new CachingRewindableIterator( - new EntityIteratorAdapter( aWhereClause, anOrderByClause, nrArticlesPerPage, - MirGlobal.localizer().dataModel().adapterModel(), "content", nrArticlesPerPage, anOffset) + new EntityIteratorAdapter( aWhereClause, anOrderByClause, nrEntitiesPerListPage, + MirGlobal.localizer().dataModel().adapterModel(), "content", nrEntitiesPerListPage, anOffset) ); responseData.put("nexturl", null); @@ -405,13 +385,13 @@ public class ServletModuleContent extends ServletModule responseData.put("offset" , new Integer(anOffset).toString()); responseData.put("thisurl" , urlBuilder.getQuery()); - if (count>=anOffset+nrArticlesPerPage) { - urlBuilder.setValue("offset", (anOffset + nrArticlesPerPage)); + if (count>=anOffset+nrEntitiesPerListPage) { + urlBuilder.setValue("offset", (anOffset + nrEntitiesPerListPage)); responseData.put("nexturl" , urlBuilder.getQuery()); } if (anOffset>0) { - urlBuilder.setValue("offset", Math.max(anOffset - nrArticlesPerPage, 0)); + urlBuilder.setValue("offset", Math.max(anOffset - nrEntitiesPerListPage, 0)); responseData.put("prevurl" , urlBuilder.getQuery()); } @@ -419,12 +399,12 @@ public class ServletModuleContent extends ServletModule responseData.put("from" , Integer.toString(anOffset+1)); responseData.put("count", Integer.toString(count)); - responseData.put("to", Integer.toString(Math.min(anOffset+nrArticlesPerPage, count))); + responseData.put("to", Integer.toString(Math.min(anOffset+nrEntitiesPerListPage, count))); responseData.put("offset" , Integer.toString(anOffset)); responseData.put("order", anOrderByClause); responseData.put("where" , aWhereClause); - ServletHelper.generateResponse(aResponse.getWriter(), responseData, listTemplate); + ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator); } catch (Throwable e) { throw new ServletModuleFailure(e); diff --git a/source/mircoders/servlet/ServletModuleFileEdit.java b/source/mircoders/servlet/ServletModuleFileEdit.java index 87803e34..99f4d62f 100755 --- a/source/mircoders/servlet/ServletModuleFileEdit.java +++ b/source/mircoders/servlet/ServletModuleFileEdit.java @@ -59,7 +59,7 @@ import mir.util.URLBuilder; * in the config file. * * @author $Author: zapata $ - * @version $Revision: 1.13.2.1 $ $Date: 2003/06/19 02:24:13 $ + * @version $Revision: 1.13.2.2 $ $Date: 2003/09/03 17:49:40 $ * */ @@ -137,10 +137,6 @@ public class ServletModuleFileEdit extends ServletModule } dirFilter = new FileFunctions.DirectoryFilter(); - - templateListString =configuration.getString("ServletModule.FileEdit.ListTemplate"); - templateObjektString =configuration.getString("ServletModule.FileEdit.ObjektTemplate"); - templateConfirmString =configuration.getString("ServletModule.FileEdit.ConfirmTemplate"); } public List getEntries() { @@ -255,7 +251,7 @@ public class ServletModuleFileEdit extends ServletModule responseData.put("subdirectory", aSubDirectory); responseData.put("entry", aDirectory.getName()); - ServletHelper.generateResponse(aResponse.getWriter(), responseData, templateListString); + ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator); } catch (Throwable e) { throw new ServletModuleFailure(e); @@ -295,7 +291,7 @@ public class ServletModuleFileEdit extends ServletModule responseData.put("subdirectory", aSubDirectory); responseData.put("returnurl", urlBuilder.getQuery()); - ServletHelper.generateResponse(aResponse.getWriter(), responseData, templateObjektString); + ServletHelper.generateResponse(aResponse.getWriter(), responseData, editGenerator); } } catch (Throwable e) { diff --git a/source/mircoders/servlet/ServletModuleHidden.java b/source/mircoders/servlet/ServletModuleHidden.java index b5635711..6ae6d20a 100755 --- a/source/mircoders/servlet/ServletModuleHidden.java +++ b/source/mircoders/servlet/ServletModuleHidden.java @@ -29,22 +29,24 @@ */ package mircoders.servlet; -import java.util.*; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import mir.entity.EntityList; -import mir.entity.adapter.*; -import mir.log.LoggerWrapper; -import mir.misc.HTMLTemplateProcessor; -import mir.util.*; -import mir.servlet.*; -import mir.servlet.ServletModuleFailure; -import mir.storage.StorageObjectFailure; -import mircoders.module.ModuleContent; +import java.util.Iterator; +import java.util.Locale; +import java.util.Map; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import mir.entity.adapter.EntityIteratorAdapter; +import mir.log.LoggerWrapper; +import mir.servlet.ServletModule; +import mir.servlet.ServletModuleExc; +import mir.servlet.ServletModuleFailure; +import mir.storage.StorageObjectFailure; +import mir.util.CachingRewindableIterator; +import mir.util.HTTPRequestParser; +import mir.util.JDBCStringRoutines; +import mircoders.global.MirGlobal; +import mircoders.module.ModuleContent; import mircoders.storage.DatabaseContent; -import mircoders.global.*; /* * ServletModuleHidden - output of so called "censored" articles @@ -62,7 +64,6 @@ public class ServletModuleHidden extends ServletModule super(); logger = new LoggerWrapper("ServletModule.Hidden"); - templateListString = configuration.getString("ServletModule.Hidden.ListTemplate"); try { mainModule = new ModuleContent(DatabaseContent.getInstance()); @@ -98,7 +99,7 @@ public class ServletModuleHidden extends ServletModule responseData.put("articles", articleList); } - ServletHelper.generateResponse(res.getWriter(), responseData, templateListString); + ServletHelper.generateResponse(res.getWriter(), responseData, listGenerator); } catch (Throwable e) { throw new ServletModuleFailure(e); diff --git a/source/mircoders/servlet/ServletModuleImages.java b/source/mircoders/servlet/ServletModuleImages.java index 70e5b84f..23642640 100755 --- a/source/mircoders/servlet/ServletModuleImages.java +++ b/source/mircoders/servlet/ServletModuleImages.java @@ -34,11 +34,12 @@ import mir.servlet.ServletModule; import mir.storage.StorageObjectFailure; import mircoders.module.ModuleImages; import mircoders.storage.DatabaseImages; +import mircoders.global.*; /* * ServletModuleImages - * - * @version $Id: ServletModuleImages.java,v 1.26.2.1 2003/08/13 02:43:56 zapata Exp $ + * @version $Id: ServletModuleImages.java,v 1.26.2.2 2003/09/03 17:49:40 zapata Exp $ * @author RK, the mir-coders group */ @@ -52,16 +53,14 @@ public class ServletModuleImages extends ServletModuleUploadedMedia private ServletModuleImages() { super(); logger = new LoggerWrapper("ServletModule.Images"); - entityName = "image"; moduleName = "Images"; - templateListString = configuration.getString("ServletModule.Images.ListTemplate"); - templateObjektString = configuration.getString("ServletModule.Images.ObjektTemplate"); - templateConfirmString = configuration.getString("ServletModule.Images.ConfirmTemplate"); try { + model = MirGlobal.localizer().dataModel().adapterModel(); + definition = "image"; mainModule = new ModuleImages(DatabaseImages.getInstance()); } - catch (StorageObjectFailure e) { + catch (Throwable e) { logger.error("Initialization of ServletModuleImages failed!: " + e.getMessage()); } } diff --git a/source/mircoders/servlet/ServletModuleLanguage.java b/source/mircoders/servlet/ServletModuleLanguage.java index 724d73f2..d6526cd9 100755 --- a/source/mircoders/servlet/ServletModuleLanguage.java +++ b/source/mircoders/servlet/ServletModuleLanguage.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 mircoders.servlet; @@ -34,6 +34,7 @@ import mir.servlet.ServletModule; import mir.storage.StorageObjectFailure; import mircoders.module.ModuleLanguage; import mircoders.storage.DatabaseLanguage; +import mircoders.global.*; /* * ServletModuleLanguage - @@ -52,14 +53,12 @@ public class ServletModuleLanguage extends ServletModule super(); logger = new LoggerWrapper("ServletModule.Language"); - templateListString = configuration.getString("ServletModule.Language.ListTemplate"); - templateObjektString = configuration.getString("ServletModule.Language.ObjektTemplate"); - templateConfirmString = configuration.getString("ServletModule.Language.ConfirmTemplate"); - try { + model = MirGlobal.localizer().dataModel().adapterModel(); + definition = "language"; mainModule = new ModuleLanguage(DatabaseLanguage.getInstance()); } - catch (StorageObjectFailure e) { + catch (Throwable e) { logger.error("Initialization of ServletModuleLanguage failed: " + e.getMessage()); } } diff --git a/source/mircoders/servlet/ServletModuleMediafolder.java b/source/mircoders/servlet/ServletModuleMediafolder.java index ac353500..bb33dd24 100755 --- a/source/mircoders/servlet/ServletModuleMediafolder.java +++ b/source/mircoders/servlet/ServletModuleMediafolder.java @@ -1,85 +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 mircoders.servlet; - -/** - * Title: Mir - * Description: - * @author rk - * @version 02 - */ - -import java.util.GregorianCalendar; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import mir.log.LoggerWrapper; -import mir.misc.StringUtil; -import mir.servlet.ServletModule; -import mir.storage.StorageObjectFailure; -import mircoders.module.ModuleMediafolder; -import mircoders.storage.DatabaseMediafolder; -import freemarker.template.SimpleHash; -import freemarker.template.SimpleScalar; - - -public class ServletModuleMediafolder extends ServletModule -{ - public static ServletModule getInstance() { return instance; } - private static ServletModuleMediafolder instance = new ServletModuleMediafolder(); - - private ServletModuleMediafolder() { - super(); - logger = new LoggerWrapper("ServletModule.Mediafolder"); - - templateListString = configuration.getString("ServletModule.Mediafolder.ListTemplate"); - templateObjektString = configuration.getString("ServletModule.Mediafolder.ObjektTemplate"); - templateConfirmString = configuration.getString("ServletModule.Mediafolder.ConfirmTemplate"); - - try { - mainModule = new ModuleMediafolder(DatabaseMediafolder.getInstance()); - } - catch (StorageObjectFailure e) { - logger.error("Failed to initialize ServletModuleMediafolder: " + e.getMessage()); - } - } - - public void add(HttpServletRequest req, HttpServletResponse res) - { - SimpleHash mergeData = new SimpleHash(); - mergeData.put("new", "1"); - String now = StringUtil.date2webdbDate(new GregorianCalendar()); -// date auf now - mergeData.put("date", new SimpleScalar(now)); - deliver(req, res, mergeData, templateObjektString); - } - +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, but you are not obligated to do so. + * If you do not wish to do so, delete this exception statement from your version. + */ +package mircoders.servlet; + +/** + * + */ + +import java.util.GregorianCalendar; +import java.util.Map; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import mir.log.LoggerWrapper; +import mir.misc.StringUtil; +import mir.servlet.ServletModule; +import mir.storage.StorageObjectFailure; +import mircoders.module.ModuleMediafolder; +import mircoders.storage.DatabaseMediafolder; + +public class ServletModuleMediafolder extends ServletModule +{ + public static ServletModule getInstance() { return instance; } + private static ServletModuleMediafolder instance = new ServletModuleMediafolder(); + + private ServletModuleMediafolder() { + super(); + logger = new LoggerWrapper("ServletModule.Mediafolder"); + + try { + mainModule = new ModuleMediafolder(DatabaseMediafolder.getInstance()); + } + catch (StorageObjectFailure e) { + logger.error("Failed to initialize ServletModuleMediafolder: " + e.getMessage()); + } + } + + protected void initializeNewObject(Map aNewObject, HttpServletRequest aRequest, HttpServletResponse aResponse) { + aNewObject.put("date", StringUtil.date2webdbDate(new GregorianCalendar())); + } } \ No newline at end of file diff --git a/source/mircoders/servlet/ServletModuleMessage.java b/source/mircoders/servlet/ServletModuleMessage.java index efd1e6b1..a8ec504a 100755 --- a/source/mircoders/servlet/ServletModuleMessage.java +++ b/source/mircoders/servlet/ServletModuleMessage.java @@ -1,115 +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 mircoders.servlet; - -import java.net.URLEncoder; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import mir.entity.EntityList; -import mir.log.LoggerWrapper; -import mir.misc.HTMLTemplateProcessor; -import mir.servlet.ServletModule; -import mir.servlet.ServletModuleExc; -import mir.servlet.ServletModuleFailure; -import mir.storage.StorageObjectFailure; -import mircoders.module.ModuleMessage; -import mircoders.storage.DatabaseMessages; -import freemarker.template.SimpleHash; - -/** - * Title: ServletModuleMessage - * Description: - * Copyright: Copyright (c) 2001-2002 - * Company: mir-coders - * @author - * @version 1.0 - */ - - -public class ServletModuleMessage extends ServletModule -{ - - // Singelton / Kontruktor - - private static ServletModuleMessage instance = new ServletModuleMessage(); - public static ServletModule getInstance() { return instance; } - - private ServletModuleMessage() { - super(); - logger = new LoggerWrapper("ServletModule.Messages"); - - templateListString = configuration.getString("ServletModule.Messages.ListTemplate"); - templateObjektString = configuration.getString("ServletModule.Messages.ObjektTemplate"); - templateConfirmString = configuration.getString("ServletModule.Messages.ConfirmTemplate"); - - try { - mainModule = new ModuleMessage(DatabaseMessages.getInstance()); - } - catch (StorageObjectFailure e) { - logger.error("initialization of ServletModuleMessage failed!: " + e.getMessage()); - - throw new ServletModuleFailure(e); - } - } - - public void list(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc - { -// fetch and deliver - try { - SimpleHash mergeData = new SimpleHash(); - String offset = req.getParameter("offset"); - if (offset==null || offset.equals("")) offset="0"; - mergeData.put("offset",offset); - EntityList theList = mainModule.getByWhereClause(null, "webdb_create desc", (new Integer(offset)).intValue()); - mergeData.put("contentlist",theList); - if(theList.getOrder()!=null) { - mergeData.put("order", theList.getOrder()); - mergeData.put("order_encoded", URLEncoder.encode(theList.getOrder())); - } - mergeData.put("count", (new Integer(theList.getCount())).toString()); - mergeData.put("from", (new Integer(theList.getFrom())).toString()); - mergeData.put("to", (new Integer(theList.getTo())).toString()); - if (theList.hasNextBatch()) - mergeData.put("next", (new Integer(theList.getNextBatch())).toString()); - if (theList.hasPrevBatch()) - mergeData.put("prev", (new Integer(theList.getPrevBatch())).toString()); - - HTMLTemplateProcessor.process(res, templateListString, mergeData, res.getWriter(), getLocale(req), getFallbackLocale(req)); - - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, but you are not obligated to do so. + * If you do not wish to do so, delete this exception statement from your version. + */ +package mircoders.servlet; + +import java.util.Map; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import mir.log.LoggerWrapper; +import mir.servlet.ServletModule; +import mir.servlet.ServletModuleFailure; +import mircoders.global.MirGlobal; +import mircoders.module.ModuleMessage; +import mircoders.storage.DatabaseMessages; + +/** + * Title: ServletModuleMessage + * Description: + * Copyright: Copyright (c) 2001-2002 + * Company: mir-coders + * @author + * @version 1.0 + */ + + +public class ServletModuleMessage extends ServletModule +{ + private static ServletModuleMessage instance = new ServletModuleMessage(); + public static ServletModule getInstance() { return instance; } + + private ServletModuleMessage() { + super(); + logger = new LoggerWrapper("ServletModule.Messages"); + + try { + model = MirGlobal.localizer().dataModel().adapterModel(); + definition = "internalMessage"; + mainModule = new ModuleMessage(DatabaseMessages.getInstance()); + } + catch (Throwable e) { + logger.error("initialization of ServletModuleMessage failed!: " + e.getMessage()); + + throw new ServletModuleFailure(e); + } + } + + protected void initializeNewObject(Map aNewObject, HttpServletRequest aRequest, HttpServletResponse aResponse) { + aNewObject.put("creator", ServletHelper.getUserName(aRequest)); + } +} diff --git a/source/mircoders/servlet/ServletModuleOpenIndy.java b/source/mircoders/servlet/ServletModuleOpenIndy.java index 5b21ad44..c75380aa 100755 --- a/source/mircoders/servlet/ServletModuleOpenIndy.java +++ b/source/mircoders/servlet/ServletModuleOpenIndy.java @@ -120,7 +120,7 @@ import mircoders.storage.DatabaseTopics; * open-postings to the newswire * * @author mir-coders group - * @version $Id: ServletModuleOpenIndy.java,v 1.89.2.6 2003/06/30 16:13:24 zapata Exp $ + * @version $Id: ServletModuleOpenIndy.java,v 1.89.2.7 2003/09/03 17:49:40 zapata Exp $ * */ @@ -354,7 +354,7 @@ public class ServletModuleOpenIndy extends ServletModule Map extraInfo = new HashMap(); extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData()); - extraInfo.put("themenPopupData", topicsModule.getTopicsAsSimpleList()); + extraInfo.put("themenPopupData", DatabaseTopics.getInstance().getPopupData()); extraInfo.put("topics", topicsModule.getTopicsList()); deliver(req, res, mergeData, extraInfo, postingFormTemplate); @@ -773,7 +773,7 @@ public class ServletModuleOpenIndy extends ServletModule } try { - mergeData.put("topics", topicsModule.getTopicsAsSimpleList()); + mergeData.put("topics", DatabaseTopics.getInstance().getPopupData()); } catch (Throwable e) { logger.debug("Can't get topics: " + e.toString()); diff --git a/source/mircoders/servlet/ServletModuleOtherMedia.java b/source/mircoders/servlet/ServletModuleOtherMedia.java index d42d748c..09406964 100755 --- a/source/mircoders/servlet/ServletModuleOtherMedia.java +++ b/source/mircoders/servlet/ServletModuleOtherMedia.java @@ -35,6 +35,7 @@ import mir.servlet.ServletModule; import mir.storage.StorageObjectFailure; import mircoders.module.ModuleUploadedMedia; import mircoders.storage.DatabaseOther; +import mircoders.global.*; /** * @@ -56,16 +57,14 @@ public class ServletModuleOtherMedia extends ServletModuleUploadedMedia { private ServletModuleOtherMedia() { super(); logger = new LoggerWrapper("ServletModule.OtherMedia"); - entityName = "otherMedia"; moduleName = "OtherMedia"; - templateListString = configuration.getString("ServletModule.OtherMedia.ListTemplate"); - templateObjektString = configuration.getString("ServletModule.OtherMedia.ObjektTemplate"); - templateConfirmString = configuration.getString("ServletModule.OtherMedia.ConfirmTemplate"); try { + model = MirGlobal.localizer().dataModel().adapterModel(); + definition = "otherMedia"; mainModule = new ModuleUploadedMedia(DatabaseOther.getInstance()); } - catch (StorageObjectFailure e) { + catch (Throwable e) { logger.error("servletmodule otherMedia could not be initialized: " + e.getMessage()); } } diff --git a/source/mircoders/servlet/ServletModuleTopics.java b/source/mircoders/servlet/ServletModuleTopics.java index d2a39161..63fdd7c9 100755 --- a/source/mircoders/servlet/ServletModuleTopics.java +++ b/source/mircoders/servlet/ServletModuleTopics.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. */ @@ -35,18 +35,20 @@ import mir.servlet.ServletModule; import mir.storage.StorageObjectFailure; import mircoders.module.ModuleTopics; import mircoders.storage.DatabaseTopics; +import mircoders.global.*; -/* - * ServletModuleTopics - * +/** * - * - * @author RK + *

Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 */ public class ServletModuleTopics extends ServletModule { -// Singelton / Constructor private static ServletModuleTopics instance = new ServletModuleTopics(); public static ServletModule getInstance() { return instance; } @@ -54,14 +56,12 @@ public class ServletModuleTopics extends ServletModule super(); logger = new LoggerWrapper("ServletModule.Topics"); - templateListString = configuration.getString("ServletModule.Themen.ListTemplate"); - templateObjektString = configuration.getString("ServletModule.Themen.ObjektTemplate"); - templateConfirmString = configuration.getString("ServletModule.Themen.ConfirmTemplate"); - try { + model = MirGlobal.localizer().dataModel().adapterModel(); + definition = "topic"; mainModule = new ModuleTopics(DatabaseTopics.getInstance()); } - catch (StorageObjectFailure e) { + catch (Throwable e) { logger.error("Initialization of ServletModuleTopics failed!: " + e.getMessage()); } } diff --git a/source/mircoders/servlet/ServletModuleUploadedMedia.java b/source/mircoders/servlet/ServletModuleUploadedMedia.java index 556d18c1..6dddfa73 100755 --- a/source/mircoders/servlet/ServletModuleUploadedMedia.java +++ b/source/mircoders/servlet/ServletModuleUploadedMedia.java @@ -83,8 +83,6 @@ import mircoders.storage.DatabaseContent; */ public abstract class ServletModuleUploadedMedia extends ServletModule { - protected int nrMediaPerPage = 20; - protected String entityName = "uploadedMedia"; protected String moduleName = "UploadedMedia"; public static ServletModule getInstance() { @@ -94,7 +92,14 @@ public abstract class ServletModuleUploadedMedia extends ServletModule { public ServletModuleUploadedMedia() { super(); + definition = "uploadedMedia"; logger = new LoggerWrapper("ServletModule.UploadedMedia"); + try { + model = MirGlobal.localizer().dataModel().adapterModel(); + } + catch (Throwable t) { + throw new ServletModuleFailure(t); + } } public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse) @@ -231,7 +236,7 @@ public abstract class ServletModuleUploadedMedia extends ServletModule { responseData.put("medialist", aList); addExtraData(responseData); - ServletHelper.generateResponse(aResponse.getWriter(), responseData, templateListString); + ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator); } catch (Throwable t) { throw new ServletModuleFailure(t); @@ -255,8 +260,8 @@ public abstract class ServletModuleUploadedMedia extends ServletModule { Object mediaList = new CachingRewindableIterator( - new EntityIteratorAdapter(aWhereClause, anOrderByClause, nrMediaPerPage, - MirGlobal.localizer().dataModel().adapterModel(), entityName, nrMediaPerPage, anOffset) + new EntityIteratorAdapter(aWhereClause, anOrderByClause, nrEntitiesPerListPage, + model, definition, nrEntitiesPerListPage, anOffset) ); count = mainModule.getSize(aWhereClause); @@ -278,18 +283,18 @@ public abstract class ServletModuleUploadedMedia extends ServletModule { urlBuilder.setValue("offset", anOffset); thisUrl = urlBuilder.getQuery(); - if (count >= anOffset + nrMediaPerPage) { - urlBuilder.setValue("offset", anOffset + nrMediaPerPage); + if (count >= anOffset + nrEntitiesPerListPage) { + urlBuilder.setValue("offset", anOffset + nrEntitiesPerListPage); nextPageUrl = urlBuilder.getQuery(); } if (anOffset > 0) { - urlBuilder.setValue("offset", Math.max(anOffset - nrMediaPerPage, 0)); + urlBuilder.setValue("offset", Math.max(anOffset - nrEntitiesPerListPage, 0)); previousPageUrl = urlBuilder.getQuery(); } returnUploadedMediaList(aRequest, aResponse, mediaList, - anOffset+1, anOffset+nrMediaPerPage, count, thisUrl, + anOffset+1, anOffset+nrEntitiesPerListPage, count, thisUrl, nextPageUrl, previousPageUrl); } catch (Throwable e) { @@ -376,7 +381,7 @@ public abstract class ServletModuleUploadedMedia extends ServletModule { responseData.put("nrmedia", new Integer(nrMedia)); responseData.put("mediafields", mediaFields); - responseData.put("edittemplate", templateObjektString); + responseData.put("edittemplate", editGenerator); responseData.put("module", moduleName); addExtraData(responseData); @@ -397,14 +402,14 @@ public abstract class ServletModuleUploadedMedia extends ServletModule { try { Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)}); EntityAdapter object = - MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter(entityName, mainModule.getById(idParam)); + model.makeEntityAdapter(definition, mainModule.getById(idParam)); responseData.put("uploadedmedia", object); responseData.put("new", Boolean.FALSE); responseData.put("articleid", null); responseData.put("commentid", null); responseData.put("returnurl", null); - responseData.put("edittemplate", templateObjektString); + responseData.put("edittemplate", editGenerator); responseData.put("module", moduleName); addExtraData(responseData); diff --git a/source/mircoders/servlet/ServletModuleUsers.java b/source/mircoders/servlet/ServletModuleUsers.java index 7dd44fab..25e824c4 100755 --- a/source/mircoders/servlet/ServletModuleUsers.java +++ b/source/mircoders/servlet/ServletModuleUsers.java @@ -1,35 +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 mircoders.servlet; - +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, but you are not obligated to do so. + * If you do not wish to do so, delete this exception statement from your version. + */ + +package mircoders.servlet; + import java.util.HashMap; import java.util.Iterator; import java.util.List; @@ -52,331 +52,328 @@ import mir.util.URLBuilder; import mircoders.entity.EntityUsers; import mircoders.global.MirGlobal; import mircoders.module.ModuleUsers; -import mircoders.storage.DatabaseUsers; - -/* - * ServletModuleUsers - - * liefert HTML fuer Users - * - * - * @author RK - */ - -public class ServletModuleUsers extends ServletModule -{ - private String editTemplate; - private String listTemplate; - - private static ServletModuleUsers instance = new ServletModuleUsers(); - public static ServletModule getInstance() { return instance; } - protected ModuleUsers usersModule; - - private ServletModuleUsers() { - super(); - logger = new LoggerWrapper("ServletModule.Users"); - - listTemplate = configuration.getString("ServletModule.Users.ListTemplate"); - editTemplate = configuration.getString("ServletModule.Users.ObjektTemplate"); - templateConfirmString = configuration.getString("ServletModule.Users.ConfirmTemplate"); - - try { - usersModule = new ModuleUsers(DatabaseUsers.getInstance()); - mainModule = usersModule; - } - catch (StorageObjectFailure e) { - logger.debug("initialization of ServletModuleUsers failed!: " + e.getMessage()); - } - } - - public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { - String idParam = aRequest.getParameter("id"); - - if (idParam == null) - throw new ServletModuleExc("ServletModuleUser.edit: invalid call: (id) not specified"); - - try { - EntityUsers user = (EntityUsers) mainModule.getById(idParam); - MirGlobal.accessControl().user().assertMayEditUser(ServletHelper.getUser(aRequest), user); - - showUser(idParam, false, aRequest, aResponse); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - public void add(HttpServletRequest aRequest, HttpServletResponse aResponse) - throws ServletModuleExc - { - try { - MirGlobal.accessControl().user().assertMayAddUsers(ServletHelper.getUser(aRequest)); - - showUser(null, false, aRequest, aResponse); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - public String validatePassword(EntityUsers aUser, HTTPRequestParser aRequestParser) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure - { - if ( (aRequestParser.getParameter("newpassword") != null && - aRequestParser.getParameter("newpassword").length() > 0) || - (aRequestParser.getParameter("newpassword2") != null && - aRequestParser.getParameter("newpassword2").length() > 0) - ) { - String newPassword = aRequestParser.getParameterWithDefault("newpassword", ""); - String newPassword2 = aRequestParser.getParameterWithDefault("newpassword2", ""); - String oldPassword = aRequestParser.getParameterWithDefault("oldpassword", ""); - - try { - if (!usersModule.checkUserPassword(aUser, oldPassword)) { - throw new ServletModuleUserExc("user.error.incorrectpassword", new String[] {}); - } - } - catch (Throwable t) { - throw new ServletModuleFailure(t); - } - - - if (newPassword.length() == 0 || newPassword2.length() == 0) { - throw new ServletModuleUserExc("user.error.missingpasswords", new String[] {}); - } - - if (!newPassword.equals(newPassword2)) { - throw new ServletModuleUserExc("user.error.passwordmismatch", new String[] {}); - } - - return newPassword; - } - else - return null; - } - - public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse) - throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure - { - try { - MirGlobal.accessControl().user().assertMayAddUsers(ServletHelper.getUser(aRequest)); - - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - Map withValues = getIntersectingValues(aRequest, mainModule.getStorageObject()); - - String newPassword=validatePassword(ServletHelper.getUser(aRequest), requestParser); - if (newPassword!=null) - withValues.put("password", newPassword); - else - throw new ServletModuleUserExc("user.error.missingpassword", new String[] {}); - - String id = mainModule.add(withValues); - if (requestParser.hasParameter("returnurl")) - redirect(aResponse, requestParser.getParameter("returnurl")); - else - list(aRequest, aResponse); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure - { - try { - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - EntityUsers user = (EntityUsers) mainModule.getById(requestParser.getParameter("id")); - MirGlobal.accessControl().user().assertMayEditUser(ServletHelper.getUser(aRequest), user); - - Map withValues = getIntersectingValues(aRequest, mainModule.getStorageObject()); - if (!withValues.containsKey("is_admin")) - withValues.put("is_admin","0"); - - String newPassword=validatePassword(ServletHelper.getUser(aRequest), requestParser); - if (newPassword!=null) - withValues.put("password", MirGlobal.localizer().adminInterface().makePasswordDigest(newPassword)); - - mainModule.set(withValues); - - if (requestParser.hasParameter("returnurl")) - redirect(aResponse, requestParser.getParameter("returnurl")); - else - list(aRequest, aResponse); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - public void updatepassword(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure - { - try { - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - EntityUsers user = (EntityUsers) mainModule.getById(requestParser.getParameter("id")); - MirGlobal.accessControl().user().assertMayChangeUserPassword(ServletHelper.getUser(aRequest), user); - - String newPassword=validatePassword(ServletHelper.getUser(aRequest), requestParser); - if (newPassword!=null) { - user.setValueForProperty("password", MirGlobal.localizer().adminInterface().makePasswordDigest(newPassword)); - user.update(); - - // hackish: to make sure the cached logged in user is up-to-date: - ServletHelper.setUser(aRequest, (EntityUsers) mainModule.getById(ServletHelper.getUser(aRequest).getId())); - } - - if (requestParser.hasParameter("returnurl")) - redirect(aResponse, requestParser.getParameter("returnurl")); - else - redirect(aResponse, ""); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - - int offset = requestParser.getIntegerWithDefault("offset", 0); - - returnUserList(aRequest, aResponse, offset); - } - - public void returnUserList( - HttpServletRequest aRequest, - HttpServletResponse aResponse, - int anOffset) throws ServletModuleExc { - - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - URLBuilder urlBuilder = new URLBuilder(); - EntityAdapterModel model; - int count; - int nrUsersPerPage = 20; - - try { - Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}); - model = MirGlobal.localizer().dataModel().adapterModel(); - - Object userList = - new CachingRewindableIterator( - new EntityIteratorAdapter( "", "login", nrUsersPerPage, - MirGlobal.localizer().dataModel().adapterModel(), "user", nrUsersPerPage, anOffset) - ); - - responseData.put("nexturl", null); - responseData.put("prevurl", null); - - count=mainModule.getSize(""); - - urlBuilder.setValue("module", "Users"); - urlBuilder.setValue("do", "list"); - - urlBuilder.setValue("offset", anOffset); - responseData.put("offset" , new Integer(anOffset).toString()); - responseData.put("thisurl" , urlBuilder.getQuery()); - - if (count>=anOffset+nrUsersPerPage) { - urlBuilder.setValue("offset", (anOffset + nrUsersPerPage)); - responseData.put("nexturl" , urlBuilder.getQuery()); - } - - if (anOffset>0) { - urlBuilder.setValue("offset", Math.max(anOffset - nrUsersPerPage, 0)); - responseData.put("prevurl" , urlBuilder.getQuery()); - } - - responseData.put("users", userList); - responseData.put("mayDeleteUsers", new Boolean(MirGlobal.accessControl().user().mayDeleteUsers(ServletHelper.getUser(aRequest)))); - responseData.put("mayAddUsers", new Boolean(MirGlobal.accessControl().user().mayAddUsers(ServletHelper.getUser(aRequest)))); - responseData.put("mayEditUsers", new Boolean(MirGlobal.accessControl().user().mayEditUsers(ServletHelper.getUser(aRequest)))); - - responseData.put("from" , Integer.toString(anOffset+1)); - responseData.put("count", Integer.toString(count)); - responseData.put("to", Integer.toString(Math.min(anOffset+nrUsersPerPage, count))); - responseData.put("offset" , Integer.toString(anOffset)); - - ServletHelper.generateResponse(aResponse.getWriter(), responseData, listTemplate); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - public void showUser(String anId, boolean anOnlyPassword, HttpServletRequest aRequest, HttpServletResponse aResponse) - throws ServletModuleExc { - try { - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}); - EntityAdapterModel model = MirGlobal.localizer().dataModel().adapterModel(); - Map user; - URLBuilder urlBuilder = new URLBuilder(); - - urlBuilder.setValue("module", "Users"); - if (anOnlyPassword) - urlBuilder.setValue("do", "changepassword"); - else - urlBuilder.setValue("do", "edit"); - urlBuilder.setValue("id", anId); - urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl")); - - if (anId!=null) { - responseData.put("new", Boolean.FALSE); - user = model.makeEntityAdapter("user", mainModule.getById(anId)); - } - else { - List fields = DatabaseUsers.getInstance().getFields(); - responseData.put("new", Boolean.TRUE); - user = new HashMap(); - Iterator i = fields.iterator(); - while (i.hasNext()) { - user.put(i.next(), null); - } - - MirGlobal.localizer().adminInterface().initializeArticle(user); - } - responseData.put("user", user); - responseData.put("passwordonly", new Boolean(anOnlyPassword)); - - responseData.put("returnurl", requestParser.getParameter("returnurl")); - responseData.put("thisurl", urlBuilder.getQuery()); - - ServletHelper.generateResponse(aResponse.getWriter(), responseData, editTemplate); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - public void delete(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleUserExc, ServletModuleExc, ServletModuleFailure { - try { - EntityUsers user = (EntityUsers) mainModule.getById(aRequest.getParameter("id")); - - MirGlobal.accessControl().user().assertMayDeleteUser(ServletHelper.getUser(aRequest), user); - - super.delete(aRequest, aResponse); - } - catch (Throwable t) { - throw new ServletModuleFailure(t); - } - } - - public void changepassword(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { - String idParam = aRequest.getParameter("id"); - - if (idParam == null) - throw new ServletModuleExc("ServletModuleUser.edit: invalid call: (id) not specified"); - - try { - EntityUsers user = (EntityUsers) mainModule.getById(idParam); - MirGlobal.accessControl().user().assertMayChangeUserPassword(ServletHelper.getUser(aRequest), user); - - showUser(idParam, true, aRequest, aResponse); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - -} - +import mircoders.storage.DatabaseUsers; +import mircoders.global.*; + +/** + * + *

Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ +public class ServletModuleUsers extends ServletModule +{ + private static ServletModuleUsers instance = new ServletModuleUsers(); + public static ServletModule getInstance() { return instance; } + protected ModuleUsers usersModule; + + private ServletModuleUsers() { + super(); + logger = new LoggerWrapper("ServletModule.Users"); + + try { + model = MirGlobal.localizer().dataModel().adapterModel(); + definition = "user"; + usersModule = new ModuleUsers(DatabaseUsers.getInstance()); + mainModule = usersModule; + } + catch (Throwable e) { + logger.debug("initialization of ServletModuleUsers failed!: " + e.getMessage()); + } + } + + public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc + { + String idParam = aRequest.getParameter("id"); + + if (idParam == null) + throw new ServletModuleExc("ServletModuleUser.edit: invalid call: (id) not specified"); + + try { + EntityUsers user = (EntityUsers) mainModule.getById(idParam); + MirGlobal.accessControl().user().assertMayEditUser(ServletHelper.getUser(aRequest), user); + + showUser(idParam, false, aRequest, aResponse); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + public void add(HttpServletRequest aRequest, HttpServletResponse aResponse) + throws ServletModuleExc + { + try { + MirGlobal.accessControl().user().assertMayAddUsers(ServletHelper.getUser(aRequest)); + + showUser(null, false, aRequest, aResponse); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + public String validatePassword(EntityUsers aUser, HTTPRequestParser aRequestParser) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure + { + if ( (aRequestParser.getParameter("newpassword") != null && + aRequestParser.getParameter("newpassword").length() > 0) || + (aRequestParser.getParameter("newpassword2") != null && + aRequestParser.getParameter("newpassword2").length() > 0) + ) { + String newPassword = aRequestParser.getParameterWithDefault("newpassword", ""); + String newPassword2 = aRequestParser.getParameterWithDefault("newpassword2", ""); + String oldPassword = aRequestParser.getParameterWithDefault("oldpassword", ""); + + try { + if (!usersModule.checkUserPassword(aUser, oldPassword)) { + throw new ServletModuleUserExc("user.error.incorrectpassword", new String[] {}); + } + } + catch (Throwable t) { + throw new ServletModuleFailure(t); + } + + + if (newPassword.length() == 0 || newPassword2.length() == 0) { + throw new ServletModuleUserExc("user.error.missingpasswords", new String[] {}); + } + + if (!newPassword.equals(newPassword2)) { + throw new ServletModuleUserExc("user.error.passwordmismatch", new String[] {}); + } + + return newPassword; + } + else + return null; + } + + public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse) + throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure + { + try { + MirGlobal.accessControl().user().assertMayAddUsers(ServletHelper.getUser(aRequest)); + + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + Map withValues = getIntersectingValues(aRequest, mainModule.getStorageObject()); + + String newPassword=validatePassword(ServletHelper.getUser(aRequest), requestParser); + if (newPassword!=null) + withValues.put("password", newPassword); + else + throw new ServletModuleUserExc("user.error.missingpassword", new String[] {}); + + String id = mainModule.add(withValues); + if (requestParser.hasParameter("returnurl")) + redirect(aResponse, requestParser.getParameter("returnurl")); + else + list(aRequest, aResponse); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure + { + try { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + EntityUsers user = (EntityUsers) mainModule.getById(requestParser.getParameter("id")); + MirGlobal.accessControl().user().assertMayEditUser(ServletHelper.getUser(aRequest), user); + + Map withValues = getIntersectingValues(aRequest, mainModule.getStorageObject()); + if (!withValues.containsKey("is_admin")) + withValues.put("is_admin","0"); + + String newPassword=validatePassword(ServletHelper.getUser(aRequest), requestParser); + if (newPassword!=null) + withValues.put("password", MirGlobal.localizer().adminInterface().makePasswordDigest(newPassword)); + + mainModule.set(withValues); + + if (requestParser.hasParameter("returnurl")) + redirect(aResponse, requestParser.getParameter("returnurl")); + else + list(aRequest, aResponse); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + public void updatepassword(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure + { + try { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + EntityUsers user = (EntityUsers) mainModule.getById(requestParser.getParameter("id")); + MirGlobal.accessControl().user().assertMayChangeUserPassword(ServletHelper.getUser(aRequest), user); + + String newPassword=validatePassword(ServletHelper.getUser(aRequest), requestParser); + if (newPassword!=null) { + user.setValueForProperty("password", MirGlobal.localizer().adminInterface().makePasswordDigest(newPassword)); + user.update(); + + // hackish: to make sure the cached logged in user is up-to-date: + ServletHelper.setUser(aRequest, (EntityUsers) mainModule.getById(ServletHelper.getUser(aRequest).getId())); + } + + if (requestParser.hasParameter("returnurl")) + redirect(aResponse, requestParser.getParameter("returnurl")); + else + redirect(aResponse, ""); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc + { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + + int offset = requestParser.getIntegerWithDefault("offset", 0); + + returnUserList(aRequest, aResponse, offset); + } + + public void returnUserList( + HttpServletRequest aRequest, + HttpServletResponse aResponse, + int anOffset) throws ServletModuleExc { + +// ML: to be deleted, support for 3 extra vars to be added + + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + URLBuilder urlBuilder = new URLBuilder(); + EntityAdapterModel model; + int count; + + try { + Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}); + model = MirGlobal.localizer().dataModel().adapterModel(); + + Object userList = + new CachingRewindableIterator( + new EntityIteratorAdapter( "", "login", nrEntitiesPerListPage, + MirGlobal.localizer().dataModel().adapterModel(), "user", nrEntitiesPerListPage, anOffset) + ); + + responseData.put("nexturl", null); + responseData.put("prevurl", null); + + count=mainModule.getSize(""); + + urlBuilder.setValue("module", "Users"); + urlBuilder.setValue("do", "list"); + + urlBuilder.setValue("offset", anOffset); + responseData.put("offset" , new Integer(anOffset).toString()); + responseData.put("thisurl" , urlBuilder.getQuery()); + + if (count>=anOffset+nrEntitiesPerListPage) { + urlBuilder.setValue("offset", (anOffset + nrEntitiesPerListPage)); + responseData.put("nexturl" , urlBuilder.getQuery()); + } + + if (anOffset>0) { + urlBuilder.setValue("offset", Math.max(anOffset - nrEntitiesPerListPage, 0)); + responseData.put("prevurl" , urlBuilder.getQuery()); + } + + responseData.put("users", userList); + responseData.put("mayDeleteUsers", new Boolean(MirGlobal.accessControl().user().mayDeleteUsers(ServletHelper.getUser(aRequest)))); + responseData.put("mayAddUsers", new Boolean(MirGlobal.accessControl().user().mayAddUsers(ServletHelper.getUser(aRequest)))); + responseData.put("mayEditUsers", new Boolean(MirGlobal.accessControl().user().mayEditUsers(ServletHelper.getUser(aRequest)))); + + responseData.put("from" , Integer.toString(anOffset+1)); + responseData.put("count", Integer.toString(count)); + responseData.put("to", Integer.toString(Math.min(anOffset+nrEntitiesPerListPage, count))); + responseData.put("offset" , Integer.toString(anOffset)); + + ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + public void showUser(String anId, boolean anOnlyPassword, HttpServletRequest aRequest, HttpServletResponse aResponse) + throws ServletModuleExc { + try { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}); + EntityAdapterModel model = MirGlobal.localizer().dataModel().adapterModel(); + Map user; + URLBuilder urlBuilder = new URLBuilder(); + + urlBuilder.setValue("module", "Users"); + if (anOnlyPassword) + urlBuilder.setValue("do", "changepassword"); + else + urlBuilder.setValue("do", "edit"); + urlBuilder.setValue("id", anId); + urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl")); + + if (anId!=null) { + responseData.put("new", Boolean.FALSE); + user = model.makeEntityAdapter("user", mainModule.getById(anId)); + } + else { + List fields = DatabaseUsers.getInstance().getFields(); + responseData.put("new", Boolean.TRUE); + user = new HashMap(); + Iterator i = fields.iterator(); + while (i.hasNext()) { + user.put(i.next(), null); + } + + MirGlobal.localizer().adminInterface().initializeArticle(user); + } + responseData.put("user", user); + responseData.put("passwordonly", new Boolean(anOnlyPassword)); + + responseData.put("returnurl", requestParser.getParameter("returnurl")); + responseData.put("thisurl", urlBuilder.getQuery()); + + ServletHelper.generateResponse(aResponse.getWriter(), responseData, editGenerator); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + public void delete(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleUserExc, ServletModuleExc, ServletModuleFailure { + try { + EntityUsers user = (EntityUsers) mainModule.getById(aRequest.getParameter("id")); + + MirGlobal.accessControl().user().assertMayDeleteUser(ServletHelper.getUser(aRequest), user); + + super.delete(aRequest, aResponse); + } + catch (Throwable t) { + throw new ServletModuleFailure(t); + } + } + + public void changepassword(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc + { + String idParam = aRequest.getParameter("id"); + + if (idParam == null) + throw new ServletModuleExc("ServletModuleUser.edit: invalid call: (id) not specified"); + + try { + EntityUsers user = (EntityUsers) mainModule.getById(idParam); + MirGlobal.accessControl().user().assertMayChangeUserPassword(ServletHelper.getUser(aRequest), user); + + showUser(idParam, true, aRequest, aResponse); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } +} + diff --git a/source/mircoders/servlet/ServletModuleVideo.java b/source/mircoders/servlet/ServletModuleVideo.java index de487f89..2499be32 100755 --- a/source/mircoders/servlet/ServletModuleVideo.java +++ b/source/mircoders/servlet/ServletModuleVideo.java @@ -35,42 +35,38 @@ import mir.servlet.ServletModule; import mir.storage.StorageObjectFailure; import mircoders.module.ModuleUploadedMedia; import mircoders.storage.DatabaseVideo; +import mircoders.global.*; -/* - * +/** * - * @author br1 + *

Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 */ public class ServletModuleVideo extends ServletModuleUploadedMedia { - - //private static DatabaseRights dbRights; - - // Singelton / Contructor private static ServletModuleVideo instance = new ServletModuleVideo(); public static ServletModule getInstance() { return instance; } - private ServletModuleVideo() { super(); logger = new LoggerWrapper("ServletModule.Video"); - entityName = "video"; moduleName = "Video"; - templateListString = configuration.getString("ServletModule.Video.ListTemplate"); - templateObjektString = configuration.getString("ServletModule.Video.ObjektTemplate"); - templateConfirmString = configuration.getString("ServletModule.Video.ConfirmTemplate"); try { + model = MirGlobal.localizer().dataModel().adapterModel(); + definition = "video"; mainModule = new ModuleUploadedMedia(DatabaseVideo.getInstance()); - //dbRights = DatabaseRights.getInstance(); } - catch (StorageObjectFailure e) { + catch (Throwable e) { logger.error("servletmodule video could not be initialized: " + e.getMessage()); } } -} - +} \ No newline at end of file diff --git a/source/mircoders/storage/DatabaseArticleType.java b/source/mircoders/storage/DatabaseArticleType.java index 9ba7abca..d6ed1826 100755 --- a/source/mircoders/storage/DatabaseArticleType.java +++ b/source/mircoders/storage/DatabaseArticleType.java @@ -39,17 +39,17 @@ package mircoders.storage; * @version 1.0 */ -import mir.log.LoggerWrapper; -import mir.storage.Database; -import mir.storage.StorageObject; +import java.util.List; + +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; - public class DatabaseArticleType extends Database implements StorageObject{ private static DatabaseArticleType instance; - private static SimpleList articletypePopupData; + private static List articletypePopupData; public synchronized static DatabaseArticleType getInstance() throws StorageObjectFailure { if (instance == null) { @@ -65,7 +65,4 @@ public class DatabaseArticleType extends Database implements StorageObject{ this.theTable = "article_type"; } - public SimpleList getPopupData() throws StorageObjectFailure { - return getPopupData("name", false); - } } diff --git a/source/mircoders/storage/DatabaseAudio.java b/source/mircoders/storage/DatabaseAudio.java index bed4e444..24d6b069 100755 --- a/source/mircoders/storage/DatabaseAudio.java +++ b/source/mircoders/storage/DatabaseAudio.java @@ -1,90 +1,84 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with any library licensed under the Apache Software License, - * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library - * (or with modified versions of the above that use the same license as the above), - * and distribute linked combinations including the two. You must obey the - * GNU General Public License in all respects for all of the code used other than - * the above mentioned libraries. If you modify this file, you may extend this - * exception to your version of the file, but you are not obligated to do so. - * If you do not wish to do so, delete this exception statement from your version. - */ -package mircoders.storage; - -import java.util.GregorianCalendar; - -import mir.entity.Entity; -import mir.log.LoggerWrapper; -import mir.misc.StringUtil; -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; - -public class DatabaseAudio extends Database implements StorageObject{ - - private static DatabaseAudio instance; - private static SimpleList publisherPopupData; - - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseAudio getInstance() { - if (instance == null) { - instance = new DatabaseAudio(); - } - return instance; - } - - private DatabaseAudio() throws StorageObjectFailure { - super(); - logger = new LoggerWrapper("Database.Audio"); - - hasTimestamp = true; - theTable = "audio"; - theCoreTable = "media"; - theEntityClass = mircoders.entity.EntityAudio.class; - } - - public SimpleList getPopupData() throws StorageObjectFailure { - return getPopupData("title", true); - } - - public void update(Entity theEntity) throws StorageObjectFailure { - String date = theEntity.getValue("date"); - if (date == null) { - date = StringUtil.date2webdbDate(new GregorianCalendar()); - theEntity.setValueForProperty("date", date); - } - - super.update(theEntity); - } - - public String insert(Entity theEntity) throws StorageObjectFailure { - String date = theEntity.getValue("date"); - if (date == null) { - date = StringUtil.date2webdbDate(new GregorianCalendar()); - theEntity.setValueForProperty("date", date); - } - return super.insert(theEntity); - } - -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, but you are not obligated to do so. + * If you do not wish to do so, delete this exception statement from your version. + */ +package mircoders.storage; + +import java.util.GregorianCalendar; + +import mir.entity.Entity; +import mir.log.LoggerWrapper; +import mir.misc.StringUtil; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; + +public class DatabaseAudio extends Database implements StorageObject{ + + private static DatabaseAudio instance; + + // the following *has* to be sychronized cause this static method + // could get preemted and we could end up with 2 instances of DatabaseFoo.. + // see the "Singletons with needles and thread" article at JavaWorld -mh + public synchronized static DatabaseAudio getInstance() { + if (instance == null) { + instance = new DatabaseAudio(); + } + return instance; + } + + private DatabaseAudio() throws StorageObjectFailure { + super(); + logger = new LoggerWrapper("Database.Audio"); + + hasTimestamp = true; + theTable = "audio"; + theCoreTable = "media"; + theEntityClass = mircoders.entity.EntityAudio.class; + } + + public void update(Entity theEntity) throws StorageObjectFailure { + String date = theEntity.getValue("date"); + if (date == null) { + date = StringUtil.date2webdbDate(new GregorianCalendar()); + theEntity.setValueForProperty("date", date); + } + + super.update(theEntity); + } + + public String insert(Entity theEntity) throws StorageObjectFailure { + String date = theEntity.getValue("date"); + if (date == null) { + date = StringUtil.date2webdbDate(new GregorianCalendar()); + theEntity.setValueForProperty("date", date); + } + return super.insert(theEntity); + } + +} diff --git a/source/mircoders/storage/DatabaseComment.java b/source/mircoders/storage/DatabaseComment.java index 3151c997..56f3e336 100755 --- a/source/mircoders/storage/DatabaseComment.java +++ b/source/mircoders/storage/DatabaseComment.java @@ -30,15 +30,14 @@ package mircoders.storage; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Statement; - -import mir.log.LoggerWrapper; -import mir.storage.Database; -import mir.storage.StorageObject; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; + +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; /** * This class implements the access to the comment-table for the @@ -67,10 +66,6 @@ public class DatabaseComment extends Database implements StorageObject{ this.theEntityClass = mircoders.entity.EntityComment.class; } - public SimpleList getPopupData() throws StorageObjectFailure { - return getPopupData("title", true); - } - public boolean deleteByContentId(String id) throws StorageObjectFailure { Statement stmt = null; Connection con = null; diff --git a/source/mircoders/storage/DatabaseCommentStatus.java b/source/mircoders/storage/DatabaseCommentStatus.java index c2f5cc8a..7cd02d85 100755 --- a/source/mircoders/storage/DatabaseCommentStatus.java +++ b/source/mircoders/storage/DatabaseCommentStatus.java @@ -39,11 +39,10 @@ package mircoders.storage; * @version 1.0 */ -import mir.log.LoggerWrapper; -import mir.storage.Database; -import mir.storage.StorageObject; +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; public class DatabaseCommentStatus extends Database implements StorageObject{ @@ -64,8 +63,4 @@ public class DatabaseCommentStatus extends Database implements StorageObject{ theTable = "comment_status"; logger = new LoggerWrapper("Database.CommentStatus"); } - - public SimpleList getPopupData() throws StorageObjectFailure { - return getPopupData("name", false); - } } \ No newline at end of file diff --git a/source/mircoders/storage/DatabaseCommentToMedia.java b/source/mircoders/storage/DatabaseCommentToMedia.java index 9868d6bc..e0424d40 100755 --- a/source/mircoders/storage/DatabaseCommentToMedia.java +++ b/source/mircoders/storage/DatabaseCommentToMedia.java @@ -30,24 +30,24 @@ package mircoders.storage; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.Statement; - -import mir.entity.EntityList; -import mir.log.LoggerWrapper; -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectExc; -import mir.storage.StorageObjectFailure; -import mircoders.entity.EntityComment; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.Statement; + +import mir.entity.EntityList; +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectExc; +import mir.storage.StorageObjectFailure; +import mircoders.entity.EntityComment; import mircoders.entity.EntityUploadedMedia; /** * implements abstract DB connection to the comment_x_media SQL table * * @author RK, mir-coders group - * @version $Id: DatabaseCommentToMedia.java,v 1.3 2003/05/03 00:21:22 zapata Exp $ + * @version $Id: DatabaseCommentToMedia.java,v 1.3.2.1 2003/09/03 17:49:41 zapata Exp $ * */ @@ -72,33 +72,6 @@ public class DatabaseCommentToMedia extends Database implements StorageObject{ theEntityClass = mir.entity.GenericEntity.class; } - /** - * get all the media-files belonging to a comment entity - * - */ - public EntityList getMedia(EntityComment comment) throws StorageObjectFailure { - EntityList returnList = null; - if (comment != null) { - // get all to_topic from media_x_topic - String id = comment.getId(); - String subselect = "id in (select media_id from " + theTable + - " where comment_id=" + id + ")"; - - try { - // media should stay in uploaded order. this is especially important - // for photo stories which require a specific chronologic order. - // this is why we have the the second parameter "id" - returnList = DatabaseMedia.getInstance().selectByWhereClause(subselect, - "id", -1); - } - catch (Throwable e) { - logger.debug("-- get media failed " + e.toString()); - throw new StorageObjectFailure("-- get media failed ", e); - } - } - return returnList; - } - public boolean hasMedia(EntityComment comment) throws StorageObjectFailure, StorageObjectExc { if (comment != null) { diff --git a/source/mircoders/storage/DatabaseContent.java b/source/mircoders/storage/DatabaseContent.java index c1d494b4..b28c5e0c 100755 --- a/source/mircoders/storage/DatabaseContent.java +++ b/source/mircoders/storage/DatabaseContent.java @@ -30,16 +30,13 @@ package mircoders.storage; -import java.sql.Connection; -import java.sql.Statement; - -import mir.entity.EntityList; -import mir.entity.EntityRelation; -import mir.log.LoggerWrapper; -import mir.storage.Database; -import mir.storage.StorageObject; +import java.sql.Connection; +import java.sql.Statement; + +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; import mir.storage.StorageObjectFailure; -import mircoders.entity.EntityContent; /** * this class implements the access to the content-table @@ -50,7 +47,6 @@ import mircoders.entity.EntityContent; public class DatabaseContent extends Database implements StorageObject { private static DatabaseContent instance; - private static EntityRelation relationComments; // Contructors / Singleton @@ -72,8 +68,6 @@ public class DatabaseContent extends Database implements StorageObject { theCoreTable="media"; logger = new LoggerWrapper("Database.Content"); - relationComments = - new EntityRelation("id", "to_media", DatabaseComment.getInstance(), EntityRelation.TO_MANY); theEntityClass = mircoders.entity.EntityContent.class; } diff --git a/source/mircoders/storage/DatabaseContentToMedia.java b/source/mircoders/storage/DatabaseContentToMedia.java index 8cb8a561..5f147b66 100755 --- a/source/mircoders/storage/DatabaseContentToMedia.java +++ b/source/mircoders/storage/DatabaseContentToMedia.java @@ -30,24 +30,24 @@ package mircoders.storage; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.Statement; - -import mir.entity.EntityList; -import mir.log.LoggerWrapper; -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectExc; -import mir.storage.StorageObjectFailure; -import mircoders.entity.EntityContent; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.Statement; + +import mir.entity.EntityList; +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectExc; +import mir.storage.StorageObjectFailure; +import mircoders.entity.EntityContent; import mircoders.entity.EntityUploadedMedia; /** * implements abstract DB connection to the content_x_media SQL table * * @author RK, mir-coders group - * @version $Id: DatabaseContentToMedia.java,v 1.19 2003/05/03 00:21:22 zapata Exp $ + * @version $Id: DatabaseContentToMedia.java,v 1.19.2.1 2003/09/03 17:49:41 zapata Exp $ * */ @@ -72,33 +72,6 @@ public class DatabaseContentToMedia extends Database implements StorageObject{ theEntityClass = mir.entity.GenericEntity.class; } - /** - * get all the media-files belonging to a content entity - * - */ - public EntityList getMedia(EntityContent content) throws StorageObjectFailure { - EntityList returnList = null; - if (content != null) { - // get all to_topic from media_x_topic - String id = content.getId(); - String subselect = "id in (select media_id from " + theTable + - " where content_id=" + id + ")"; - - try { - // media should stay in uploaded order. this is especially important - // for photo stories which require a specific chronologic order. - // this is why we have the the second parameter "id" - returnList = DatabaseMedia.getInstance().selectByWhereClause(subselect, - "id", -1); - } - catch (Throwable e) { - logger.debug("-- get media failed " + e.toString()); - throw new StorageObjectFailure("-- get media failed ", e); - } - } - return returnList; - } - public boolean hasMedia(EntityContent content) throws StorageObjectFailure, StorageObjectExc { if (content != null) { diff --git a/source/mircoders/storage/DatabaseContentToTopics.java b/source/mircoders/storage/DatabaseContentToTopics.java index 7475e909..4a696e41 100755 --- a/source/mircoders/storage/DatabaseContentToTopics.java +++ b/source/mircoders/storage/DatabaseContentToTopics.java @@ -30,21 +30,21 @@ package mircoders.storage; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.Vector; - -import mir.entity.EntityList; -import mir.log.LoggerWrapper; -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import mircoders.entity.EntityContent; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Vector; + +import mir.entity.EntityList; +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; +import mircoders.entity.EntityContent; import mircoders.entity.EntityTopics; /** diff --git a/source/mircoders/storage/DatabaseImageColor.java b/source/mircoders/storage/DatabaseImageColor.java index f857d708..bbf37db6 100755 --- a/source/mircoders/storage/DatabaseImageColor.java +++ b/source/mircoders/storage/DatabaseImageColor.java @@ -30,11 +30,9 @@ package mircoders.storage; -import mir.log.LoggerWrapper; -import mir.storage.Database; +import mir.log.LoggerWrapper; +import mir.storage.Database; import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; /** * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle @@ -45,7 +43,6 @@ import freemarker.template.SimpleList; public class DatabaseImageColor extends Database implements StorageObject{ private static DatabaseImageColor instance; - private static SimpleList publisherPopupData; // the following *has* to be sychronized cause this static method // could get preemted and we could end up with 2 instances of DatabaseFoo.. @@ -64,7 +61,4 @@ public class DatabaseImageColor extends Database implements StorageObject{ theTable = "img_color"; } - public SimpleList getPopupData() throws StorageObjectFailure { - return getPopupData("name", true); - } } diff --git a/source/mircoders/storage/DatabaseImageFormat.java b/source/mircoders/storage/DatabaseImageFormat.java index 310987dd..26f2a8d8 100755 --- a/source/mircoders/storage/DatabaseImageFormat.java +++ b/source/mircoders/storage/DatabaseImageFormat.java @@ -30,11 +30,9 @@ package mircoders.storage; -import mir.log.LoggerWrapper; -import mir.storage.Database; +import mir.log.LoggerWrapper; +import mir.storage.Database; import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; /** * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle @@ -45,7 +43,6 @@ import freemarker.template.SimpleList; public class DatabaseImageFormat extends Database implements StorageObject{ private static DatabaseImageFormat instance; - private static SimpleList publisherPopupData; // the following *has* to be sychronized cause this static method // could get preemted and we could end up with 2 instances of DatabaseFoo.. @@ -63,9 +60,4 @@ public class DatabaseImageFormat extends Database implements StorageObject{ hasTimestamp = false; theTable = "img_format"; } - - public SimpleList getPopupData() throws StorageObjectFailure { - return getPopupData("name", true); - } - } diff --git a/source/mircoders/storage/DatabaseImageLayout.java b/source/mircoders/storage/DatabaseImageLayout.java index 1fac5a32..641f9035 100755 --- a/source/mircoders/storage/DatabaseImageLayout.java +++ b/source/mircoders/storage/DatabaseImageLayout.java @@ -30,11 +30,9 @@ package mircoders.storage; -import mir.log.LoggerWrapper; -import mir.storage.Database; +import mir.log.LoggerWrapper; +import mir.storage.Database; import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; /** * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle @@ -45,7 +43,6 @@ import freemarker.template.SimpleList; public class DatabaseImageLayout extends Database implements StorageObject{ private static DatabaseImageLayout instance; - private static SimpleList publisherPopupData; // the following *has* to be sychronized cause this static method // could get preemted and we could end up with 2 instances of DatabaseFoo.. @@ -64,9 +61,4 @@ public class DatabaseImageLayout extends Database implements StorageObject{ hasTimestamp = false; theTable = "img_layout"; } - - public SimpleList getPopupData() throws StorageObjectFailure { - return getPopupData("name", true); - } - } diff --git a/source/mircoders/storage/DatabaseImageType.java b/source/mircoders/storage/DatabaseImageType.java index 377f1f73..a924eb59 100755 --- a/source/mircoders/storage/DatabaseImageType.java +++ b/source/mircoders/storage/DatabaseImageType.java @@ -1,69 +1,63 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with any library licensed under the Apache Software License, - * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library - * (or with modified versions of the above that use the same license as the above), - * and distribute linked combinations including the two. You must obey the - * GNU General Public License in all respects for all of the code used other than - * the above mentioned libraries. If you modify this file, you may extend this - * exception to your version of the file, but you are not obligated to do so. - * If you do not wish to do so, delete this exception statement from your version. - */ -package mircoders.storage; - -import mir.log.LoggerWrapper; -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; - -/** - * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle - * - * - */ - -public class DatabaseImageType extends Database implements StorageObject{ - private static DatabaseImageType instance; - - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseImageType getInstance() { - if (instance == null) { - instance = new DatabaseImageType(); - } - return instance; - } - - private DatabaseImageType() { - super(); - logger = new LoggerWrapper("Database.ImageType"); - - hasTimestamp = false; - theTable = "img_type"; - } - - public SimpleList getPopupData() throws StorageObjectFailure { - return getPopupData("name", true); - } - -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, but you are not obligated to do so. + * If you do not wish to do so, delete this exception statement from your version. + */ +package mircoders.storage; + +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; + +/** + * + *

Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ + +public class DatabaseImageType extends Database implements StorageObject{ + private static DatabaseImageType instance; + + public synchronized static DatabaseImageType getInstance() { + if (instance == null) { + instance = new DatabaseImageType(); + } + return instance; + } + + private DatabaseImageType() { + super(); + logger = new LoggerWrapper("Database.ImageType"); + + hasTimestamp = false; + theTable = "img_type"; + } +} diff --git a/source/mircoders/storage/DatabaseImages.java b/source/mircoders/storage/DatabaseImages.java index d525df4a..681fbaa9 100755 --- a/source/mircoders/storage/DatabaseImages.java +++ b/source/mircoders/storage/DatabaseImages.java @@ -1,102 +1,91 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with any library licensed under the Apache Software License, - * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library - * (or with modified versions of the above that use the same license as the above), - * and distribute linked combinations including the two. You must obey the - * GNU General Public License in all respects for all of the code used other than - * the above mentioned libraries. If you modify this file, you may extend this - * exception to your version of the file, but you are not obligated to do so. - * If you do not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - -import java.util.GregorianCalendar; - -import mir.entity.Entity; -import mir.log.LoggerWrapper; -import mir.misc.StringUtil; -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; - -/** - * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle - * - * - */ - -public class DatabaseImages extends Database implements StorageObject{ - - private static DatabaseImages instance; - private static SimpleList publisherPopupData; - - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseImages getInstance() { - if (instance == null) { - instance = new DatabaseImages(); - } - return instance; - } - - private DatabaseImages() { - super(); - - logger = new LoggerWrapper("Database.Images"); - - hasTimestamp = true; - theTable = "images"; - theCoreTable = "media"; - theEntityClass = mircoders.entity.EntityImages.class; - } - - public SimpleList getPopupData() throws StorageObjectFailure { - return getPopupData("title", true); - } - - public void update(Entity theEntity) throws StorageObjectFailure { - String date = theEntity.getValue("date"); - if (date == null) { - date = StringUtil.date2webdbDate(new GregorianCalendar()); - theEntity.setValueForProperty("date", date); - } - - super.update(theEntity); - } - - public String insert(Entity theEntity) throws StorageObjectFailure { - String date = theEntity.getValue("date"); - - if (date == null) { - date = StringUtil.date2webdbDate(new GregorianCalendar()); - theEntity.setValueForProperty("date", date); - } - - return super.insert(theEntity); - } - - // initialisierungen aus den statischen Tabellen - -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, but you are not obligated to do so. + * If you do not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + +import java.util.GregorianCalendar; +import java.util.List; + +import mir.entity.Entity; +import mir.log.LoggerWrapper; +import mir.misc.StringUtil; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; + +/** + * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle + * + * + */ + +public class DatabaseImages extends Database implements StorageObject{ + + private static DatabaseImages instance; + + public synchronized static DatabaseImages getInstance() { + if (instance == null) { + instance = new DatabaseImages(); + } + return instance; + } + + private DatabaseImages() { + super(); + + logger = new LoggerWrapper("Database.Images"); + + hasTimestamp = true; + theTable = "images"; + theCoreTable = "media"; + theEntityClass = mircoders.entity.EntityImages.class; + } + + public void update(Entity theEntity) throws StorageObjectFailure { + String date = theEntity.getValue("date"); + if (date == null) { + date = StringUtil.date2webdbDate(new GregorianCalendar()); + theEntity.setValueForProperty("date", date); + } + + super.update(theEntity); + } + + public String insert(Entity theEntity) throws StorageObjectFailure { + String date = theEntity.getValue("date"); + + if (date == null) { + date = StringUtil.date2webdbDate(new GregorianCalendar()); + theEntity.setValueForProperty("date", date); + } + + return super.insert(theEntity); + } +} diff --git a/source/mircoders/storage/DatabaseLanguage.java b/source/mircoders/storage/DatabaseLanguage.java index e0b15bc2..a1ed74da 100755 --- a/source/mircoders/storage/DatabaseLanguage.java +++ b/source/mircoders/storage/DatabaseLanguage.java @@ -1,79 +1,93 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with any library licensed under the Apache Software License, - * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library - * (or with modified versions of the above that use the same license as the above), - * and distribute linked combinations including the two. You must obey the - * GNU General Public License in all respects for all of the code used other than - * the above mentioned libraries. If you modify this file, you may extend this - * exception to your version of the file, but you are not obligated to do so. - * If you do not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - -/** - * Title: DatabaseLanguage - * Description: - * Copyright: Copyright (c) 2001 - * Company: Indymedia - * @author - * @version 1.0 - */ - -import mir.log.LoggerWrapper; -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; - - -public class DatabaseLanguage extends Database implements StorageObject{ - - private static DatabaseLanguage instance; - private static SimpleList languagePopupData; - - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseLanguage getInstance() throws - StorageObjectFailure { - if (instance == null) { - instance = new DatabaseLanguage(); - } - return instance; - } - - private DatabaseLanguage() throws StorageObjectFailure { - super(); - logger = new LoggerWrapper("Database.Language"); - - this.hasTimestamp = false; - this.theTable = "language"; - } - - public SimpleList getPopupData() throws StorageObjectFailure { - SimpleList pData = null; - pData = getPopupData("name", false); - - return pData; - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, but you are not obligated to do so. + * If you do not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + +/** + * Title: DatabaseLanguage + * Description: + * Copyright: Copyright (c) 2001 + * Company: Indymedia + * @author + * @version 1.0 + */ + +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Vector; + +import mir.entity.Entity; +import mir.entity.EntityBrowser; +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; + + +public class DatabaseLanguage extends Database implements StorageObject{ + private static DatabaseLanguage instance; + + // the following *has* to be sychronized cause this static method + // could get preemted and we could end up with 2 instances of DatabaseFoo.. + // see the "Singletons with needles and thread" article at JavaWorld -mh + public synchronized static DatabaseLanguage getInstance() throws + StorageObjectFailure { + if (instance == null) { + instance = new DatabaseLanguage(); + } + return instance; + } + + private DatabaseLanguage() throws StorageObjectFailure { + super(); + logger = new LoggerWrapper("Database.Language"); + + this.hasTimestamp = false; + this.theTable = "language"; + } + + public List getPopupData() throws StorageObjectFailure { + List result = new Vector(); + Iterator i = new EntityBrowser(this, "", "name", 100, -1, 0); + + while (i.hasNext()) { + Entity e = (Entity) i.next(); + Map entry = new HashMap(); + entry.put("key", e.getId()); + entry.put("value", e.getValue("name")); + + result.add(entry); + } + + return result; + } +} diff --git a/source/mircoders/storage/DatabaseMedia.java b/source/mircoders/storage/DatabaseMedia.java deleted file mode 100755 index ed653a56..00000000 --- a/source/mircoders/storage/DatabaseMedia.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with any library licensed under the Apache Software License, - * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library - * (or with modified versions of the above that use the same license as the above), - * and distribute linked combinations including the two. You must obey the - * GNU General Public License in all respects for all of the code used other than - * the above mentioned libraries. If you modify this file, you may extend this - * exception to your version of the file, but you are not obligated to do so. - * If you do not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - -import mir.entity.Entity; -import mir.entity.EntityRelation; -import mir.log.LoggerWrapper; -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectExc; -import mir.storage.StorageObjectFailure; - -/** - * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle - * - * - */ - -public class DatabaseMedia extends Database implements StorageObject{ - - private static DatabaseMedia instance; - private static EntityRelation relationMediaType; - - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseMedia getInstance() { - if (instance == null) { - instance = new DatabaseMedia(); - } - return instance; - } - - private DatabaseMedia() { - super(); - - logger = new LoggerWrapper("Database.Media"); - - hasTimestamp = false; - theTable="media"; - relationMediaType = - new EntityRelation("to_media_type", "id", DatabaseMediaType.getInstance(), EntityRelation.TO_ONE); - theEntityClass = mircoders.entity.EntityMedia.class; - } - - // methods - - - /** - * returns the comments that belong to the article (via entityrelation) - * where db-flag is_published is true - */ - public Entity getMediaType(Entity ent) throws StorageObjectFailure, StorageObjectExc { - try { - return relationMediaType.getOne(ent); - } - catch (Throwable e) { - logger.error("failed to get media_type: " + e.getMessage()); - throw new StorageObjectFailure("DatabaseMedia.getMediaType :" + e.getMessage(),e); - } - } - -} diff --git a/source/mircoders/storage/DatabaseMediaType.java b/source/mircoders/storage/DatabaseMediaType.java index 398acb22..cd2cf1a1 100755 --- a/source/mircoders/storage/DatabaseMediaType.java +++ b/source/mircoders/storage/DatabaseMediaType.java @@ -42,12 +42,8 @@ import mir.storage.StorageObjectFailure; */ public class DatabaseMediaType extends Database implements StorageObject{ - private static DatabaseMediaType instance; - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh public synchronized static DatabaseMediaType getInstance() { if (instance == null) { instance = new DatabaseMediaType(); diff --git a/source/mircoders/storage/DatabaseMediafolder.java b/source/mircoders/storage/DatabaseMediafolder.java index 01be6866..aaccbe4c 100755 --- a/source/mircoders/storage/DatabaseMediafolder.java +++ b/source/mircoders/storage/DatabaseMediafolder.java @@ -1,77 +1,59 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with any library licensed under the Apache Software License, - * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library - * (or with modified versions of the above that use the same license as the above), - * and distribute linked combinations including the two. You must obey the - * GNU General Public License in all respects for all of the code used other than - * the above mentioned libraries. If you modify this file, you may extend this - * exception to your version of the file, but you are not obligated to do so. - * If you do not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - -/** - * Title: Mir - * Description: Ihre Beschreibung - * Copyright: Copyright (c) 1999 - * Company: - * @author - * @version - */ - -import mir.log.LoggerWrapper; -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; - - - -public class DatabaseMediafolder extends Database implements StorageObject{ - - private static DatabaseMediafolder instance; - - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseMediafolder getInstance() { - if (instance == null) { - instance = new DatabaseMediafolder(); - } - return instance; - } - - private DatabaseMediafolder() { - super(); - - logger = new LoggerWrapper("Database.Mediafolder"); - - hasTimestamp = false; - theTable="media_folder"; - } - - public SimpleList getPopupData() throws StorageObjectFailure { - return getPopupData("name",true); - } - -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, but you are not obligated to do so. + * If you do not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + +/** + * + */ + +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; + +public class DatabaseMediafolder extends Database implements StorageObject{ + private static DatabaseMediafolder instance; + + public synchronized static DatabaseMediafolder getInstance() { + if (instance == null) { + instance = new DatabaseMediafolder(); + } + return instance; + } + + private DatabaseMediafolder() { + super(); + + logger = new LoggerWrapper("Database.Mediafolder"); + + hasTimestamp = false; + theTable="media_folder"; + } +} diff --git a/source/mircoders/storage/DatabaseOther.java b/source/mircoders/storage/DatabaseOther.java index 22f48758..712f542f 100755 --- a/source/mircoders/storage/DatabaseOther.java +++ b/source/mircoders/storage/DatabaseOther.java @@ -1,98 +1,97 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with any library licensed under the Apache Software License, - * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library - * (or with modified versions of the above that use the same license as the above), - * and distribute linked combinations including the two. You must obey the - * GNU General Public License in all respects for all of the code used other than - * the above mentioned libraries. If you modify this file, you may extend this - * exception to your version of the file, but you are not obligated to do so. - * If you do not wish to do so, delete this exception statement from your version. - */ -package mircoders.storage; - - -import java.util.GregorianCalendar; - -import mir.entity.Entity; -import mir.log.LoggerWrapper; -import mir.misc.StringUtil; -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; - -/** - * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle - * - * - */ - -public class DatabaseOther extends Database implements StorageObject{ - private static DatabaseOther instance; - - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseOther getInstance() { - if (instance == null) { - instance = new DatabaseOther(); - } - return instance; - } - - private DatabaseOther() { - super(); - - logger = new LoggerWrapper("Database.OtherMedia"); - - hasTimestamp = true; - theTable = "other_media"; - theCoreTable = "media"; - theEntityClass = mircoders.entity.EntityOther.class; - } - - public SimpleList getPopupData() throws StorageObjectFailure { - return getPopupData("title", true); - } - - public void update(Entity theEntity) throws StorageObjectFailure { - String date = theEntity.getValue("date"); - if (date == null) { - date = StringUtil.date2webdbDate(new GregorianCalendar()); - theEntity.setValueForProperty("date", date); - } - - super.update(theEntity); - } - - public String insert(Entity theEntity) throws StorageObjectFailure { - String date = theEntity.getValue("date"); - if (date == null) { - date = StringUtil.date2webdbDate(new GregorianCalendar()); - theEntity.setValueForProperty("date", date); - } - return super.insert(theEntity); - } - - // initialisierungen aus den statischen Tabellen - -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, but you are not obligated to do so. + * If you do not wish to do so, delete this exception statement from your version. + */ +package mircoders.storage; + + +import java.util.GregorianCalendar; + +import mir.entity.Entity; +import mir.log.LoggerWrapper; +import mir.misc.StringUtil; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; + +/** + * + *

Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ + +public class DatabaseOther extends Database implements StorageObject{ + private static DatabaseOther instance; + + // the following *has* to be sychronized cause this static method + // could get preemted and we could end up with 2 instances of DatabaseFoo.. + // see the "Singletons with needles and thread" article at JavaWorld -mh + public synchronized static DatabaseOther getInstance() { + if (instance == null) { + instance = new DatabaseOther(); + } + return instance; + } + + private DatabaseOther() { + super(); + + logger = new LoggerWrapper("Database.OtherMedia"); + + hasTimestamp = true; + theTable = "other_media"; + theCoreTable = "media"; + theEntityClass = mircoders.entity.EntityOther.class; + } + + public void update(Entity theEntity) throws StorageObjectFailure { + String date = theEntity.getValue("date"); + if (date == null) { + date = StringUtil.date2webdbDate(new GregorianCalendar()); + theEntity.setValueForProperty("date", date); + } + + super.update(theEntity); + } + + public String insert(Entity theEntity) throws StorageObjectFailure { + String date = theEntity.getValue("date"); + if (date == null) { + date = StringUtil.date2webdbDate(new GregorianCalendar()); + theEntity.setValueForProperty("date", date); + } + return super.insert(theEntity); + } + + // initialisierungen aus den statischen Tabellen + +} diff --git a/source/mircoders/storage/DatabaseRights.java b/source/mircoders/storage/DatabaseRights.java index 11914a85..5bdbd087 100755 --- a/source/mircoders/storage/DatabaseRights.java +++ b/source/mircoders/storage/DatabaseRights.java @@ -34,20 +34,20 @@ import mir.log.LoggerWrapper; import mir.storage.Database; import mir.storage.StorageObject; import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; /** - * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle - * * + *

Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 */ public class DatabaseRights extends Database implements StorageObject{ private static DatabaseRights instance; - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh public synchronized static DatabaseRights getInstance() { if (instance == null) { instance = new DatabaseRights(); @@ -63,9 +63,4 @@ public class DatabaseRights extends Database implements StorageObject{ hasTimestamp = false; theTable = "rights"; } - - public SimpleList getPopupData() throws StorageObjectFailure { - return getPopupData("name", true); - } - } diff --git a/source/mircoders/storage/DatabaseTopics.java b/source/mircoders/storage/DatabaseTopics.java index 2b502cb3..95f5df8b 100755 --- a/source/mircoders/storage/DatabaseTopics.java +++ b/source/mircoders/storage/DatabaseTopics.java @@ -1,72 +1,91 @@ -/* - * Copyright (C) 2001, 2002 The Mir-coders group - * - * This file is part of Mir. - * - * Mir is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * Mir is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Mir; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * In addition, as a special exception, The Mir-coders gives permission to link - * the code of this program with any library licensed under the Apache Software License, - * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library - * (or with modified versions of the above that use the same license as the above), - * and distribute linked combinations including the two. You must obey the - * GNU General Public License in all respects for all of the code used other than - * the above mentioned libraries. If you modify this file, you may extend this - * exception to your version of the file, but you are not obligated to do so. - * If you do not wish to do so, delete this exception statement from your version. - */ - -package mircoders.storage; - -import mir.log.LoggerWrapper; -import mir.storage.Database; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; - -/** - * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle - * - * - */ - -public class DatabaseTopics extends Database implements StorageObject{ - - private static DatabaseTopics instance; - - // the following *has* to be sychronized cause this static method - // could get preemted and we could end up with 2 instances of DatabaseFoo.. - // see the "Singletons with needles and thread" article at JavaWorld -mh - public synchronized static DatabaseTopics getInstance() { - if (instance == null) { - instance = new DatabaseTopics(); - } - return instance; - } - - private DatabaseTopics() throws StorageObjectFailure { - super(); - - logger = new LoggerWrapper("Database.Topics"); - - hasTimestamp = false; - theTable = "topic"; - theEntityClass = mircoders.entity.EntityTopics.class; - } - - public SimpleList getPopupData() throws StorageObjectFailure { - return getPopupData("title", true); - } -} +/* + * Copyright (C) 2001, 2002 The Mir-coders group + * + * This file is part of Mir. + * + * Mir is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * Mir is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Mir; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, The Mir-coders gives permission to link + * the code of this program with any library licensed under the Apache Software License, + * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library + * (or with modified versions of the above that use the same license as the above), + * and distribute linked combinations including the two. You must obey the + * GNU General Public License in all respects for all of the code used other than + * the above mentioned libraries. If you modify this file, you may extend this + * exception to your version of the file, but you are not obligated to do so. + * If you do not wish to do so, delete this exception statement from your version. + */ + +package mircoders.storage; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Vector; + +import mir.entity.Entity; +import mir.entity.EntityBrowser; +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; + +/** + * + *

Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 + */ + +public class DatabaseTopics extends Database implements StorageObject{ + private static DatabaseTopics instance; + + public synchronized static DatabaseTopics getInstance() { + if (instance == null) { + instance = new DatabaseTopics(); + } + return instance; + } + + private DatabaseTopics() throws StorageObjectFailure { + super(); + + logger = new LoggerWrapper("Database.Topics"); + + hasTimestamp = false; + theTable = "topic"; + theEntityClass = mircoders.entity.EntityTopics.class; + } + + public List getPopupData() throws StorageObjectFailure { + List result = new Vector(); + Iterator i = new EntityBrowser(this, "", "title", 100, -1, 0); + + while (i.hasNext()) { + Entity e = (Entity) i.next(); + Map entry = new HashMap(); + entry.put("key", e.getId()); + entry.put("value", e.getValue("title")); + + result.add(entry); + } + + return result; + } +} diff --git a/source/mircoders/storage/DatabaseUploadedMedia.java b/source/mircoders/storage/DatabaseUploadedMedia.java index 0e077ed7..8c2000f0 100755 --- a/source/mircoders/storage/DatabaseUploadedMedia.java +++ b/source/mircoders/storage/DatabaseUploadedMedia.java @@ -30,16 +30,17 @@ package mircoders.storage; -import mir.entity.Entity; -import mir.entity.EntityRelation; -import mir.log.LoggerWrapper; -import mir.storage.Database; -import mir.storage.StorageObject; +import java.util.Iterator; + +import mir.entity.Entity; +import mir.entity.EntityBrowser; +import mir.log.LoggerWrapper; +import mir.storage.Database; +import mir.storage.StorageObject; import mir.storage.StorageObjectFailure; public class DatabaseUploadedMedia extends Database implements StorageObject { private static DatabaseUploadedMedia instance; - private static EntityRelation relationMediaType; public synchronized static DatabaseUploadedMedia getInstance() { if (instance == null ) { @@ -56,7 +57,6 @@ public class DatabaseUploadedMedia extends Database implements StorageObject { theTable="uploaded_media"; theCoreTable="media"; - relationMediaType = new EntityRelation("to_media_type", "id", DatabaseMediaType.getInstance(), EntityRelation.TO_ONE); theEntityClass = mircoders.entity.EntityUploadedMedia.class; } @@ -68,7 +68,9 @@ public class DatabaseUploadedMedia extends Database implements StorageObject { public Entity getMediaType(Entity ent) throws StorageObjectFailure { Entity type=null; try { - type = relationMediaType.getOne(ent); + Iterator i = new EntityBrowser(DatabaseMediaType.getInstance(), ent.getValue("to_media_type") + " = id" , "id", 1); + if (i.hasNext()) + type = (Entity) i.next(); } catch (Throwable t) { logger.error("DatabaseUploadedMedia :: failed to get media_type: " + t.getMessage()); diff --git a/source/mircoders/storage/DatabaseUsers.java b/source/mircoders/storage/DatabaseUsers.java index 89e1ae6e..29dddacc 100755 --- a/source/mircoders/storage/DatabaseUsers.java +++ b/source/mircoders/storage/DatabaseUsers.java @@ -34,12 +34,15 @@ import mir.log.LoggerWrapper; import mir.storage.Database; import mir.storage.StorageObject; import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; /** - * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle - * * + *

Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 */ public class DatabaseUsers extends Database implements StorageObject{ @@ -65,8 +68,4 @@ public class DatabaseUsers extends Database implements StorageObject{ theTable = "webdb_users"; theEntityClass = mircoders.entity.EntityUsers.class; } - - public SimpleList getPopupData() throws StorageObjectFailure { - return getPopupData("login", true); - } } diff --git a/source/mircoders/storage/DatabaseVideo.java b/source/mircoders/storage/DatabaseVideo.java index a51d5b1f..5f2b1382 100755 --- a/source/mircoders/storage/DatabaseVideo.java +++ b/source/mircoders/storage/DatabaseVideo.java @@ -30,7 +30,7 @@ package mircoders.storage; -import java.util.GregorianCalendar; +import java.util.*; import mir.entity.Entity; import mir.log.LoggerWrapper; @@ -38,18 +38,20 @@ import mir.misc.StringUtil; import mir.storage.Database; import mir.storage.StorageObject; import mir.storage.StorageObjectFailure; -import freemarker.template.SimpleList; /** - * Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle - * * + *

Title:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author not attributable + * @version 1.0 */ public class DatabaseVideo extends Database implements StorageObject{ private static DatabaseVideo instance; - private static SimpleList publisherPopupData; // the following *has* to be sychronized cause this static method // could get preemted and we could end up with 2 instances of DatabaseFoo.. @@ -72,10 +74,6 @@ public class DatabaseVideo extends Database implements StorageObject{ theEntityClass = mircoders.entity.EntityVideo.class; } - public SimpleList getPopupData() throws StorageObjectFailure { - return getPopupData("title", true); - } - public void update(Entity theEntity) throws StorageObjectFailure { String date = theEntity.getValue("date"); if (date == null) { diff --git a/templates/admin/EDITFUNCTIONS.template b/templates/admin/EDITFUNCTIONS.template index 14a7a517..d9830b9a 100755 --- a/templates/admin/EDITFUNCTIONS.template +++ b/templates/admin/EDITFUNCTIONS.template @@ -31,8 +31,23 @@ - + + + + + + + + + + + + + ${utility.encodeHTML(fieldcontent)} + + + diff --git a/templates/admin/FUNCTIONS.template b/templates/admin/FUNCTIONS.template index b9c68bca..2b1eeed3 100755 --- a/templates/admin/FUNCTIONS.template +++ b/templates/admin/FUNCTIONS.template @@ -10,59 +10,6 @@ - -creates a full table incl. edit/delete entry.id - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- ${indexVariable} - -   -
- ${entry[indexVariable]} - - ${lang("delete")} - | ${lang("edit")} -
- ${data.count} ${lang("records")} / ${lang("show_from_to", data.from, data.to)} -
-
- @@ -133,28 +80,6 @@ -creates browse links, only called if necessary - -

- -

- - - - - - - - - - - - -
- -

-
- extra navigation

@@ -175,11 +100,9 @@ -

[<] ${lang("back")}  

+

[<] ${lang("back")}  

- - diff --git a/templates/admin/FUNCTIONS_media.template b/templates/admin/FUNCTIONS_media.template index a2a04bf5..3a0932c1 100755 --- a/templates/admin/FUNCTIONS_media.template +++ b/templates/admin/FUNCTIONS_media.template @@ -3,6 +3,8 @@ not used for image-list because imagelist uses other display method + +
@@ -67,90 +69,85 @@ - - - - - - - - - - - - + - - - class="listrow1"class="listrow2" > - - - - - - - - - - - - + - - + + + + + + + + + + + +
- ${lang("media.icon")} - ${lang("media.title")} - ${lang("media.format")} - ${lang("media.size")} - ${lang("media.mediafolder")} - ${lang("media.creator")} -  
- - - - - - - - ${entry.title}  -
${entry.description}
-
- ${entry.media_descr}  - - ${entry.human_readable_size}  - - - ${entry.mediafolder.name} -   - - ${entry.creator}  -   - - ${lang("attach")} - - - ${lang("attach")} - - ${lang("delete")} - | - ${lang("edit")} - - -
- ${count} ${lang("records")} / ${lang("show_from_to", from, to)} -
- - ${lang("list.previous")}  - - - ${lang("list.next")} + + + + + + + + + + + + + + + class="listrow1"class="listrow2" > + - - - - - -
+ ${lang("media.icon")} + ${lang("media.title")} + ${lang("media.format")} + ${lang("media.size")} + ${lang("media.mediafolder")} + ${lang("media.creator")} +  
+ + + + + -
${lang("no_matches_found")}
+
+ ${entry.title}  +
${entry.description}
+
+ ${entry.media_descr}  + + ${entry.human_readable_size}  + + + ${entry.mediafolder.name} +   + + ${entry.creator}  +   + + ${lang("attach")} + + + ${lang("attach")} + + ${lang("delete")} + | + ${lang("edit")} + + +
+ ${count} ${lang("records")} / ${lang("show_from_to", from, to)} +
+ + + + + +

${lang("no_matches_found")}

+
diff --git a/templates/admin/abuse.log.template b/templates/admin/abuse.log.template index f80a9395..73882a58 100755 --- a/templates/admin/abuse.log.template +++ b/templates/admin/abuse.log.template @@ -23,7 +23,7 @@ - ${l.timestamp.format("yyyy-MM-dd HH:mm")} + ${l.timestamp.format(config["Mir.DefaultDateTimeFormat"])} ${l.ip} diff --git a/templates/admin/articletype.template b/templates/admin/articletype.template index 5d7c98f9..2a21ed1b 100755 --- a/templates/admin/articletype.template +++ b/templates/admin/articletype.template @@ -4,46 +4,36 @@ - - - - - - - - - - - - - - - - - - - - - - - - -
- ${lang("articletype.id")}: - - ${data.id} -
- - + + + + + + + + + + + + + + + + - + -
- - -

[<] ${lang("back")}  

+ + + + + + + - + diff --git a/templates/admin/articletypelist.template b/templates/admin/articletypelist.template index 937896c1..4361cfad 100755 --- a/templates/admin/articletypelist.template +++ b/templates/admin/articletypelist.template @@ -7,26 +7,14 @@ + + - - - - - - - - - - - - - - - - - - - + + + + +

${lang("no_matches_found")}

diff --git a/templates/admin/breaking.template b/templates/admin/breaking.template index 3ec12430..e84c0a85 100755 --- a/templates/admin/breaking.template +++ b/templates/admin/breaking.template @@ -1,52 +1,42 @@ - - ${config["Mir.Name"]} | ${lang("breaking.htmltitle")} - - + + ${config["Mir.Name"]} | ${lang("breaking.htmltitle")} + + - - - - - - -
- - - - - + + + - - - - + + + + + + + + + + + + + + + + + + + + - - - - - - + + + + + + + - - -
- ${lang("breaking.date")}: - - ${data.webdb_create_formatted} -
- ${lang("breaking.text")}:
${lang("breaking.textinfo")}
- -
- - - - - -
-
-

[<] ${lang("back")}

- - + + diff --git a/templates/admin/breakinglist.template b/templates/admin/breakinglist.template index 9b2cef8e..7fe2f462 100755 --- a/templates/admin/breakinglist.template +++ b/templates/admin/breakinglist.template @@ -1,50 +1,26 @@ - - ${config["Mir.Name"]} | ${lang("breakinglist.htmltitle")} - - - - + + ${config["Mir.Name"]} | ${lang("breakinglist.htmltitle")} + + + - - - configure this template here - - - - - - - - - - - - - - -

- [+] ${lang("add")}   - [<<<] ${lang("head.start")} -

- - - -

${lang("no_matches_found")}

+ + + + + + + + +

${lang("no_matches_found")}

- -

- [+] ${lang("add")}   - [<<<] ${lang("head.start")} -

- - + diff --git a/templates/admin/commentlist.template b/templates/admin/commentlist.template index a8ef1608..229f7568 100755 --- a/templates/admin/commentlist.template +++ b/templates/admin/commentlist.template @@ -98,7 +98,7 @@ class="listrow1"class="listrow2"
> - ${entry.creationdate.formatted["dd.MM.yyyy HH:mm"]}
+ ${entry.creationdate.format(config["Mir.DefaultDateTimeFormat"])}
${lang("commentlist.hidden")}-

${lang("comment.status")}:
diff --git a/templates/admin/commentstatus.template b/templates/admin/commentstatus.template index bb778275..7f0b5932 100755 --- a/templates/admin/commentstatus.template +++ b/templates/admin/commentstatus.template @@ -4,43 +4,36 @@ - + -
+ + + + + + + + + + + + + + + + + - - - - + + + + - + - - - - - - - - - - - -
- ${lang("commentstatus.id")}: - ${data.id} -
- - - - - - - -
- -

[<] ${lang("back")}  

diff --git a/templates/admin/commentstatuslist.template b/templates/admin/commentstatuslist.template index 8944f9bd..d137d287 100755 --- a/templates/admin/commentstatuslist.template +++ b/templates/admin/commentstatuslist.template @@ -5,35 +5,21 @@ - - + + + - configure this template here - - - - - - - - - - - - - - - - - -

${lang("no_matches_found")}

+ + + + + + +

${lang("no_matches_found")}

- - - diff --git a/templates/admin/content.template b/templates/admin/content.template index 2079caf5..665ae7b3 100755 --- a/templates/admin/content.template +++ b/templates/admin/content.template @@ -63,7 +63,7 @@ ${lang("content.lastchange_date")}: - ${utility.encodeHTML(article.changedate.format("yyyy-MM-dd HH:mm"))}
+ ${utility.encodeHTML(article.changedate.format(config["Mir.DefaultDateTimeFormat"]))}
@@ -72,7 +72,7 @@ ${lang("content.create_date")}: - ${utility.encodeHTML(article.creationdate.format("yyyy-MM-dd HH:mm"))}
${lang("edit")}: + ${utility.encodeHTML(article.creationdate.format(config["Mir.DefaultDateTimeFormat"]))}
${lang("edit")}:   (yyyy-mm-dd [HH:mm]) diff --git a/templates/admin/contentlist.template b/templates/admin/contentlist.template index 00d39d67..e5800105 100755 --- a/templates/admin/contentlist.template +++ b/templates/admin/contentlist.template @@ -63,8 +63,8 @@ class="listrow1"class="listrow2"
> - ${entry.creationdate.formatted["dd.MM.yyyy HH:mm"]}
- ${entry.changedate.formatted["dd.MM.yyyy HH:mm"]}
+ ${entry.creationdate.format(config["Mir.DefaultDateTimeFormat"])}
+ ${entry.changedate.format(config["Mir.DefaultDateTimeFormat"])}
Pub.- HTML- diff --git a/templates/admin/error.template b/templates/admin/error.template index 288e1565..65f7d009 100755 --- a/templates/admin/error.template +++ b/templates/admin/error.template @@ -1,20 +1,20 @@ - + ${config["Mir.Name"]} | ${lang("error.htmltitle")} - - - + + + -
+
-

${lang("error.title")}

-

${lang("error.text", config["Mir.Tech-email.address"], config["Mir.Tech-email.name"])}

-


${data.date} -- ${data.errorstring}

-

${lang("error.text2", config["Mir.Tech-email.address"], config["Mir.Tech-email.name"])}

+

${lang("error.title")}

+

${lang("error.text", config["Mir.Tech-email.address"], config["Mir.Tech-email.name"])}

+


${date.format(config["Mir.DefaultDateTimeFormat"])} -- ${errorstring}

+

${lang("error.text2", config["Mir.Tech-email.address"], config["Mir.Tech-email.name"])}

-
+
- - + + diff --git a/templates/admin/foot.template b/templates/admin/foot.template index e1432d3f..d67fe76e 100755 --- a/templates/admin/foot.template +++ b/templates/admin/foot.template @@ -1,5 +1,5 @@
- +
diff --git a/templates/admin/head.template b/templates/admin/head.template index e9ed39cb..0c942f70 100755 --- a/templates/admin/head.template +++ b/templates/admin/head.template @@ -4,7 +4,7 @@
- ${config["Mir.Name"]}   |   ${config.now.format("yyyy-MM-dd HH:mm z")} + ${config["Mir.Name"]}   |   ${config.now.format(config["Mir.DefaultDateTimeFormat"])} ${lang("head.changepassword")}   |   diff --git a/templates/admin/head_nonavi.template b/templates/admin/head_nonavi.template index 8850bb77..2238ae59 100755 --- a/templates/admin/head_nonavi.template +++ b/templates/admin/head_nonavi.template @@ -4,7 +4,7 @@
- ${config["Mir.Name"]}   |   ${config.now.format("yyyy-MM-dd HH:mm z")} + ${config["Mir.Name"]}
diff --git a/templates/admin/hiddenlist.template b/templates/admin/hiddenlist.template index 4708b164..cd2191b4 100755 --- a/templates/admin/hiddenlist.template +++ b/templates/admin/hiddenlist.template @@ -68,7 +68,7 @@
-

${lang("start.content.hidden")} | ${lang("month")}: ${data.month} , ${lang("year")}:${data.year}

+

${lang("start.content.hidden")} | ${lang("month")}: ${month} , ${lang("year")}:${year}

@@ -77,7 +77,7 @@

${lang("content.title")}: ${i.title}
${lang("content.creator")}: ${i.creator}
- ${lang("message.date")}: ${i.creationdate.formatted["dd.MM.yyyy HH:mm"]}
+ ${lang("message.date")}: ${i.creationdate.format(config["Mir.DefaultDateTimeFormat"])}

additional media, type: audio
additional media, type: video
diff --git a/templates/admin/language.template b/templates/admin/language.template index de733de8..1c20eced 100755 --- a/templates/admin/language.template +++ b/templates/admin/language.template @@ -1,33 +1,41 @@ - - ${config["Mir.Name"]} | ${lang("language.htmltitle")} - - + + ${config["Mir.Name"]} | ${lang("language.htmltitle")} + + + - - - + + + + + + + + + + + + + + + + + + + + -

- - - - - - - - - - -
- - - - - -
-
-

[<] ${lang("back")}  

- - + + + + + + + + + + diff --git a/templates/admin/languagelist.template b/templates/admin/languagelist.template index 5ee774f4..58a2eae7 100755 --- a/templates/admin/languagelist.template +++ b/templates/admin/languagelist.template @@ -4,33 +4,20 @@ - - + + - configure this template here - - - - - - - - - - - - - - - - - -

${lang("no_matches_found")}

+ + + + + + +

${lang("no_matches_found")}

- - + diff --git a/templates/admin/linksimcs.template b/templates/admin/linksimcs.template deleted file mode 100755 index ab40ab18..00000000 --- a/templates/admin/linksimcs.template +++ /dev/null @@ -1,74 +0,0 @@ - - - ${config["Mir.Name"]} | ${lang("linkimcs.htmltitle")} - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- -
- - - -
${lang("linkimcs.url")}: - -
${lang("linkimcs.sort-by")}: - -
${lang("linkimcs.language")}: - -
- - - - - -
- - - diff --git a/templates/admin/login.template b/templates/admin/login.template index 279f8c6f..0fd062c3 100755 --- a/templates/admin/login.template +++ b/templates/admin/login.template @@ -50,8 +50,8 @@ ${lang("login.language")}: diff --git a/templates/admin/mediafolder.template b/templates/admin/mediafolder.template index 0389eb9f..61ec50c5 100755 --- a/templates/admin/mediafolder.template +++ b/templates/admin/mediafolder.template @@ -5,39 +5,40 @@ - - - - -
- - - - - - - - - - - - - - - - -
- - - -
- -
-

- [<] ${lang("list")}   - [<<<] ${lang("head.start")} -

- - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/templates/admin/mediafolderlist.template b/templates/admin/mediafolderlist.template index 06b3a31c..62787b7a 100755 --- a/templates/admin/mediafolderlist.template +++ b/templates/admin/mediafolderlist.template @@ -5,53 +5,24 @@ + + + + - - - - - - - - - - - - - class="listrow1"class="listrow2" > - - - - - - - - - - - - -
${lang("mediafolder.date")}${lang("mediafolder.name")}${lang("mediafolder.location")}${lang("mediafolder.comment")}${lang("mediafolder.keywords")} 
${entry.date} ${entry.name} ${entry.place} ${entry.comment} ${entry.keywords} ${lang("delete")} - | ${lang("edit")} - | ${lang("list")}
${data.count} ${lang("records")} / - ${lang("show_from_to", data.from, data.to)} 
-

- - ${lang("list.previous")}  - - - ${lang("list.next")} - - -

${lang("no_matches_found")}

-
+ + + + + + +

${lang("no_matches_found")}

+
-

- [+] ${lang("add")}   - [<<<] ${lang("head.start")} -

- - + diff --git a/templates/admin/message.template b/templates/admin/message.template index 244b2908..d2032870 100755 --- a/templates/admin/message.template +++ b/templates/admin/message.template @@ -1,63 +1,43 @@ - - ${config["Mir.Name"]} | ${lang("message.htmltitle")} - - - - - - - - -
- - - - - - - - - + + ${config["Mir.Name"]} | ${lang("message.htmltitle")} + + + + + + - - - - - - - - - - - - - - - - - -
- ${lang("message.date")}: - ${data.date} -
- ${lang("message.textinfo")} - - - - - - -
- -
-

+ + + + + - [<] ${lang("back")}   - [<<<] ${lang("head.start")} -

- + + + + + + + + + + + + + + + - - + + + + + + + + + + diff --git a/templates/admin/messagelist.template b/templates/admin/messagelist.template index b151b25e..0782eac7 100755 --- a/templates/admin/messagelist.template +++ b/templates/admin/messagelist.template @@ -6,69 +6,24 @@ - - - -

- [+] ${lang("add")}   - [<<<] ${lang("head.start")} -

- - - - - - - - - - - - - - - - - - - - class="listrow1" - class="listrow2" - - > - - - - - - - - - + + - - -
- ${lang("message.date")} - ${lang("message.title")} /
${lang("message.creator")}
- ${lang("message.text")}
${entry.webdb_create} ${entry.title}
- ${lang("by")}: ${entry.creator}
${entry.description}  - [ ${lang("delete")} ]
- [ ${lang("edit")} ] -
${data.count} ${lang("records")} / - ${lang("show_from_to", data.from, data.to)}
- -

- - - -

${lang("no_matches_found")}

-
+ + + + + + + + +

${lang("no_matches_found")}

+
+ + - diff --git a/templates/admin/start_admin.template b/templates/admin/start_admin.template index 2b4bdb44..fd893912 100755 --- a/templates/admin/start_admin.template +++ b/templates/admin/start_admin.template @@ -142,7 +142,7 @@ ${m.title}
${m.description}
- by: ${m.creator} / ${m.webdb_create}
+ by: ${m.creator} / ${m.creationdate.format(config["Mir.DefaultDateTimeFormat"])}}

@@ -161,17 +161,17 @@
- + +

HELP-Demo:
popup small-link:    popup big-link:

newwin small-link:    newwin big-link:

- +
-   diff --git a/templates/admin/topic.template b/templates/admin/topic.template index 1c90b7dd..3fae6b8f 100755 --- a/templates/admin/topic.template +++ b/templates/admin/topic.template @@ -8,32 +8,40 @@ - + + + [module, entity.id, method])> + + - - - - - + + + + + + + - - - - - - - - - + + + + + + -

[<] ${lang("back")}  

+ + + + + + + diff --git a/templates/admin/topiclist.template b/templates/admin/topiclist.template index 21a3c584..6a08c89a 100755 --- a/templates/admin/topiclist.template +++ b/templates/admin/topiclist.template @@ -6,36 +6,32 @@ - - - - configure this template here - - - - - - - - - - - - - - - - - -

${lang("no_matches_found")}

-
- + + + + + + + + +

${lang("no_matches_found")}

+
- diff --git a/templates/admin/user.template b/templates/admin/user.template index ffcd6230..ddef833c 100755 --- a/templates/admin/user.template +++ b/templates/admin/user.template @@ -53,7 +53,7 @@ - + -- 2.11.0