From: idfx Date: Sat, 6 Nov 2004 20:09:12 +0000 (+0000) Subject: rebuilding head X-Git-Tag: BEFORE_MERGE_1_1~22 X-Git-Url: http://erislabs.net/gitweb/?p=mir.git;a=commitdiff_plain;h=6d0d5a5bda666857dc0c9f2da125de57c63a2425 rebuilding head --- diff --git a/source/Mir.java b/source/Mir.java index 6ec9e626..0277021a 100755 --- a/source/Mir.java +++ b/source/Mir.java @@ -1,354 +1,386 @@ -/* - * 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. - */ - -import java.io.IOException; -import java.lang.reflect.Method; -import java.util.*; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Vector; -import javax.servlet.ServletConfig; -import javax.servlet.ServletException; -import javax.servlet.UnavailableException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.apache.struts.util.MessageResources; -import mir.config.MirPropertiesConfiguration; -import mir.servlet.AbstractServlet; -import mir.servlet.ServletModule; -import mir.servlet.ServletModuleDispatch; -import mir.servlet.ServletModuleExc; -import mir.servlet.ServletModuleUserExc; -import mir.util.ExceptionFunctions; -import mir.util.StringRoutines; -import mircoders.entity.EntityUsers; -import mircoders.global.MirGlobal; -import mircoders.module.ModuleMessage; -import mircoders.module.ModuleUsers; -import mircoders.servlet.ServletHelper; -import mircoders.storage.DatabaseUsers; - - - - -/** - * Mir.java - main servlet, that dispatches to servletmodules - * - * @author $Author: zapata $ - * @version $Id: Mir.java,v 1.50 2003/09/03 18:29:01 zapata Exp $ - * - */ -public class Mir extends AbstractServlet { - private static ModuleUsers usersModule = null; - private static ModuleMessage messageModule = null; - private final static Map servletModuleInstanceHash = new HashMap(); - private static Locale fallbackLocale = null; - - private static List loginLanguages = null; - - protected List getLoginLanguages() throws ServletException { - synchronized (Mir.class) { - try { - if (loginLanguages == null) { - MessageResources messageResources = - MessageResources.getMessageResources("bundles.adminlocal"); - MessageResources messageResources2 = - MessageResources.getMessageResources("bundles.admin"); - - List languages = - StringRoutines.splitString(MirGlobal.config().getString("Mir.Login.Languages", "en"), ";"); - - loginLanguages = new Vector(); - - Iterator i = languages.iterator(); - - while (i.hasNext()) { - String code = (String) i.next(); - Locale locale = new Locale(code, ""); - String name = messageResources.getMessage(locale, "languagename"); - - if (name == null) { - name = messageResources2.getMessage(locale, "languagename"); - } - - if (name == null) { - name = code; - } - - Map record = new HashMap(); - record.put("name", name); - record.put("code", code); - loginLanguages.add(record); - } - } - - return loginLanguages; - } - catch (Throwable t) { - throw new ServletException(t.getMessage()); - } - } - } - - public void init(ServletConfig config) throws ServletException { - super.init(config); - - usersModule = new ModuleUsers(DatabaseUsers.getInstance()); - } - - protected String getDefaultLanguage(HttpServletRequest aRequest) { - String defaultlanguage = - MirGlobal.config().getString("Mir.Login.DefaultLanguage", ""); - - if (defaultlanguage.length() == 0) { - Locale locale = aRequest.getLocale(); - defaultlanguage = locale.getLanguage(); - } - - return defaultlanguage; - } - - protected synchronized Locale getFallbackLocale() throws ServletException { - try { - if (fallbackLocale == null) { - fallbackLocale = new Locale(MirPropertiesConfiguration.instance().getString("Mir.Admin.FallbackLanguage", "en"), ""); - } - } - catch (Throwable t) { - throw new ServletException(t.getMessage()); - } - - return fallbackLocale; - } - - public EntityUsers checkCredentials(HttpServletRequest aRequest) throws ServletException { - try { - EntityUsers user = ServletHelper.getUser(aRequest); - - String username = aRequest.getParameter("login"); - String password = aRequest.getParameter("password"); - - if (username != null && password != null) { - user = usersModule.getUserForLogin(username, password); - - - ServletHelper.setUser(aRequest, user); - } - - return user; - } - catch (Throwable t) { - t.printStackTrace(); - - throw new ServletException(t.toString()); - } - } - - public void process(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletException, IOException, UnavailableException { - try { - long startTime = System.currentTimeMillis(); - long sessionConnectTime = 0; - - HttpSession session = aRequest.getSession(true); - setNoCaching(aResponse); - Locale locale = new Locale(getDefaultLanguage(aRequest), ""); - aResponse.setContentType("text/html; charset=" + - configuration. - getString("Mir.DefaultHTMLCharset", "UTF-8")); - - EntityUsers userEntity = checkCredentials(aRequest); - - if (userEntity == null) { - String queryString = aRequest.getQueryString(); - - if ( (queryString != null) && (queryString.length() != 0) && session.getAttribute("login.target") == null && - (aRequest.getParameter("module")==null || - (!aRequest.getParameter("module").equals("login") && !aRequest.getParameter("module").equals("logout")))) { - session.setAttribute("login.target", queryString); - } - - _sendLoginPage(aResponse, aRequest); - } - else { - String moduleName = aRequest.getParameter("module"); - checkLanguage(session, aRequest); - - if ( ( (moduleName == null) || moduleName.equals(""))) { - moduleName="Admin"; - } - - - if (moduleName.equals("login")) { - String target = (String) session.getAttribute("login.target"); - - if (target != null) { - ServletHelper.redirect(aResponse, target); - } - else { - ServletHelper.redirect(aResponse, ""); - } - } - else if (moduleName.equals("logout")) { - logger.info(userEntity.getValue("login") + " has logged out"); - session.invalidate(); - _sendLoginPage(aResponse, aRequest); - return; - } - else { - try { - ServletModule servletModule = getServletModuleForName(moduleName); - ServletModuleDispatch.dispatch(servletModule, aRequest, aResponse); - - sessionConnectTime = System.currentTimeMillis() - startTime; - logger.info("EXECTIME (" + moduleName + "): " + sessionConnectTime + " ms"); - } - catch (Throwable e) { - Throwable cause = ExceptionFunctions.traceCauseException(e); - - if (cause instanceof ServletModuleUserExc) - handleUserError(aRequest, aResponse, (ServletModuleUserExc) cause); - else - handleError(aRequest, aResponse, cause); - } - - if (aRequest.getParameter("killsession")!=null) - aRequest.getSession().invalidate(); - } - } - } - catch (Throwable t) { - t.printStackTrace(); - - throw new ServletException(t.toString()); - } - } - - /** - * 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)) { - // was not found in hash... - try { - Class theServletModuleClass = null; - - try { - // first we try to get ServletModule from stern.che3.servlet - theServletModuleClass = - Class.forName("mircoders.servlet.ServletModule" + moduleName); - } - catch (ClassNotFoundException e) { - // on failure, we try to get it from lib-layer - theServletModuleClass = - Class.forName("mir.servlet.ServletModule" + moduleName); - } - - Method m = theServletModuleClass.getMethod("getInstance", null); - ServletModule smod = (ServletModule) m.invoke(null, null); - - // we put it into map for further reference - servletModuleInstanceHash.put(moduleName, smod); - - return smod; - } - catch (Exception e) { - throw new ServletModuleExc("*** error resolving classname for " + moduleName + " -- " + e.getMessage()); - } - } - else { - return (ServletModule) servletModuleInstanceHash.get(moduleName); - } - } - - private void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse, ServletModuleUserExc anException) { - try { - logger.info("user error: " + anException.getMessage()); - - Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale()}); - - MessageResources messages = MessageResources.getMessageResources("bundles.admin"); - 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, Throwable anException) { - try { - logger.error("error: " + anException); - - 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()); - } - } - - // Redirect-methods - private void _sendLoginPage(HttpServletResponse aResponse, HttpServletRequest aRequest) { - String loginTemplate = configuration.getString("Mir.LoginTemplate"); - - try { - Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale()}); - - responseData.put("defaultlanguage", getDefaultLanguage(aRequest)); - responseData.put("languages", getLoginLanguages()); - - ServletHelper.generateResponse(aResponse.getWriter(), responseData, loginTemplate); - } - catch (Throwable e) { - handleError(aRequest, aResponse, e); - } - } - - public String getServletInfo() { - return "Mir " + configuration.getString("Mir.Version"); - } -} +/* + * 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. + */ + +import mir.bundle.Bundle; +import mir.config.MirPropertiesConfiguration; +import mir.servlet.*; +import mir.util.ExceptionFunctions; +import mir.util.StringRoutines; +import mir.log.LoggerWrapper; +import mircoders.entity.EntityUsers; +import mircoders.global.MirGlobal; +import mircoders.module.ModuleUsers; +import mircoders.servlet.ServletHelper; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.UnavailableException; +import javax.servlet.http.*; +import java.io.IOException; +import java.io.PrintWriter; +import java.lang.reflect.Method; +import java.util.*; + +/** + * Mir.java - main servlet, that dispatches to servletmodules + * + * @author $Author: idfx $ + * + */ +public class Mir extends AbstractServlet { + private static ModuleUsers usersModule = null; + private final static Map servletModuleInstanceHash = new HashMap(); + private static Locale fallbackLocale = null; + + private static List loginLanguages = null; + + protected List getLoginLanguages() throws ServletException { + synchronized (Mir.class) { + try { + if (loginLanguages == null) { + List languages = + StringRoutines.splitString(MirGlobal.config().getString("Mir.Login.Languages", "en"), ";"); + + loginLanguages = new ArrayList(); + + Iterator i = languages.iterator(); + + while (i.hasNext()) { + String code = (String) i.next(); + + Bundle bundle = + MirGlobal.getBundleFactory().getBundle("etc/bundles/adminlocal", new String[] { code }); + Bundle defaultBundle = + MirGlobal.getBundleFactory().getBundle("bundles/admin", new String[] { code }); + + String name = bundle.getValue("languagename", Collections.EMPTY_LIST); + + if (name == null) { + name = defaultBundle.getValue("languagename", Collections.EMPTY_LIST); + } + + if (name == null) { + name = code; + } + + Map record = new HashMap(); + record.put("name", name); + record.put("code", code); + loginLanguages.add(record); + } + } + + return loginLanguages; + } + catch (Throwable t) { + throw new ServletException(t.getMessage()); + } + } + } + + public void init(ServletConfig config) throws ServletException { + super.init(config); + + usersModule = new ModuleUsers(); + } + + protected String getDefaultLanguage(HttpServletRequest aRequest) { + String defaultlanguage = + MirGlobal.config().getString("Mir.Login.DefaultLanguage", ""); + + if (defaultlanguage.length() == 0) { + Locale locale = aRequest.getLocale(); + defaultlanguage = locale.getLanguage(); + } + + return defaultlanguage; + } + + protected synchronized Locale getFallbackLocale() throws ServletException { + try { + if (fallbackLocale == null) { + fallbackLocale = new Locale(MirPropertiesConfiguration.instance().getString("Mir.Admin.FallbackLanguage", "en"), ""); + } + } + catch (Throwable t) { + throw new ServletException(t.getMessage()); + } + + return fallbackLocale; + } + + public EntityUsers checkCredentials(HttpServletRequest aRequest) throws ServletException { + try { + EntityUsers user = ServletHelper.getUser(aRequest); + + String username = aRequest.getParameter("login"); + String password = aRequest.getParameter("password"); + + if (username != null && password != null) { + user = usersModule.getUserForLogin(username, password); + + if (user!=null) { + ServletHelper.setUser(aRequest, user); + usersModule.recordLogin(user); + aRequest.getSession().setAttribute("sessiontracker", new SessionTracker(username, user.getId())); + } + } + + return user; + } + catch (Throwable t) { + t.printStackTrace(); + + throw new ServletException(t.toString()); + } + } + + public void process(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletException, IOException, UnavailableException { + try { + long startTime = System.currentTimeMillis(); + long sessionConnectTime = 0; + + HttpSession session = aRequest.getSession(true); + setNoCaching(aResponse); + aResponse.setContentType("text/html; charset=" + + configuration. + getString("Mir.DefaultHTMLCharset", "UTF-8")); + + EntityUsers userEntity = checkCredentials(aRequest); + + if (userEntity == null) { + String queryString = aRequest.getQueryString(); + + if ( (queryString != null) && (queryString.length() != 0) && session.getAttribute("login.target") == null && + (aRequest.getParameter("module")==null || + (!aRequest.getParameter("module").equals("login") && !aRequest.getParameter("module").equals("logout")))) { + session.setAttribute("login.target", queryString); + } + + _sendLoginPage(aResponse, aRequest); + } + else { + String moduleName = aRequest.getParameter("module"); + checkLanguage(session, aRequest); + + if ( ( (moduleName == null) || moduleName.equals(""))) { + moduleName="Admin"; + } + + + if (moduleName.equals("login")) { + String target = (String) session.getAttribute("login.target"); + + if (target != null) { + ServletHelper.redirect(aResponse, target); + } + else { + ServletHelper.redirect(aResponse, ""); + } + } + else if (moduleName.equals("logout")) { + logger.info(userEntity.getFieldValue("login") + " has logged out"); + session.invalidate(); + _sendLoginPage(aResponse, aRequest); + return; + } + else { + try { + ServletModule servletModule = getServletModuleForName(moduleName); + ServletModuleDispatch.dispatch(servletModule, aRequest, aResponse); + + sessionConnectTime = System.currentTimeMillis() - startTime; + logger.info("EXECTIME (" + moduleName + "): " + sessionConnectTime + " ms"); + } + catch (Throwable e) { + Throwable cause = ExceptionFunctions.traceCauseException(e); + + if (cause instanceof ServletModuleUserExc) + handleUserError(aRequest, aResponse, (ServletModuleUserExc) cause); + else + handleError(aRequest, aResponse, cause); + } + + if (aRequest.getParameter("killsession")!=null) + aRequest.getSession().invalidate(); + } + } + } + catch (Throwable t) { + t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); + + throw new ServletException(t.toString()); + } + } + + /** + * 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)) { + // was not found in hash... + try { + Class theServletModuleClass = null; + + try { + // first we try to get ServletModule from stern.che3.servlet + theServletModuleClass = + Class.forName("mircoders.servlet.ServletModule" + moduleName); + } + catch (ClassNotFoundException e) { + // on failure, we try to get it from lib-layer + theServletModuleClass = + Class.forName("mir.servlet.ServletModule" + moduleName); + } + + Method m = theServletModuleClass.getMethod("getInstance", null); + ServletModule smod = (ServletModule) m.invoke(null, null); + + // we put it into map for further reference + servletModuleInstanceHash.put(moduleName, smod); + + return smod; + } + catch (Exception e) { + throw new ServletModuleExc("*** error resolving classname for " + moduleName + " -- " + e.getMessage()); + } + } + else { + return (ServletModule) servletModuleInstanceHash.get(moduleName); + } + } + + private void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse, ServletModuleUserExc anException) { + try { + logger.info("user error: " + anException.getMessage()); + + Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale()}); + + Bundle bundle = + MirGlobal.getBundleFactory().getBundle("etc/bundles/adminlocal", new + String[] { getLocale(aRequest).getLanguage() }); + Bundle defaultBundle = + MirGlobal.getBundleFactory().getBundle("bundles/admin", new + String[] { getLocale(aRequest).getLanguage() }); + String message = + bundle.getValue(anException.getMessage(), Arrays.asList(anException.getParameters())); + + if (message==null) { + message = + defaultBundle.getValue(anException.getMessage(), Arrays.asList(anException.getParameters())); + } + + responseData.put("errorstring", message); + 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, Throwable anException) { + try { + logger.error("error: " + anException); + + 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()); + + try { + Throwable rootException = ExceptionFunctions.traceCauseException(anException); + + PrintWriter writer = aResponse.getWriter(); + writer.println("FATAL Error"); + writer.println("

" + rootException.toString()+"

"); + writer.println(""); + rootException.printStackTrace(writer); + writer.println(""); + writer.println(""); + writer.close(); + } + catch (Throwable t) { + + } + } + } + + // Redirect-methods + private void _sendLoginPage(HttpServletResponse aResponse, HttpServletRequest aRequest) { + String loginTemplate = configuration.getString("Mir.LoginTemplate"); + + try { + Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale()}); + + responseData.put("defaultlanguage", getDefaultLanguage(aRequest)); + responseData.put("languages", getLoginLanguages()); + + ServletHelper.generateResponse(aResponse.getWriter(), responseData, loginTemplate); + } + catch (Throwable e) { + handleError(aRequest, aResponse, e); + } + } + + public String getServletInfo() { + return "Mir " + configuration.getString("Mir.Version"); + } + + private class SessionTracker implements HttpSessionBindingListener { + private String name; + private String id; + + public SessionTracker(String aUserName, String anId) { + name = aUserName; + id = anId; + } + + public void valueBound(HttpSessionBindingEvent anEvent) { + MirGlobal.registerLogin(name, id); + } + + public void valueUnbound(HttpSessionBindingEvent anEvent) { + MirGlobal.registerLogout(name, id); + } + } +} diff --git a/source/OpenMir.java b/source/OpenMir.java index f9f260d2..20e3f9a3 100755 --- a/source/OpenMir.java +++ b/source/OpenMir.java @@ -46,7 +46,6 @@ import mircoders.servlet.ServletModuleOpenIndy; * OpenMir.java - main servlet for open posting and comment feature to articles * * @author RK 1999-2001, the mir-coders group - * @version $Id: OpenMir.java,v 1.37 2003/09/03 18:29:01 zapata Exp $ * */ @@ -54,15 +53,14 @@ import mircoders.servlet.ServletModuleOpenIndy; public class OpenMir extends AbstractServlet { public void process(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletException, IOException { - if ((configuration.getString("RootUri") == null) || - configuration.getString("RootUri").equals("")) { - configuration.setProperty("RootUri", aRequest.getContextPath()); - } + if ((configuration.getString("RootUri") == null) || + configuration.getString("RootUri").equals("")) { + configuration.setProperty("RootUri", aRequest.getContextPath()); + } long startTime = System.currentTimeMillis(); long sessionConnectTime=0; - HttpSession session = aRequest.getSession(); checkLanguage(session, aRequest); diff --git a/source/default.properties b/source/default.properties index 38988b28..0b680c8e 100755 --- a/source/default.properties +++ b/source/default.properties @@ -1,35 +1,4 @@ # -# Sample config for Mir -# by Matthias 2001-09-12 -# -# The Mir software realizes a semi-dynamic web service: -# The web server that is accessed by users has pure static -# pages. These pages are generated by the Mir software that -# consists of a collection of Java servlets and HTML templates. -# Mir uses a database server to store the data that is needed to -# build the static site. -# So there are basically three parts in this config file: -# -# a) general setup -# b) static site config -# c) dynamic admin site -# d) database config -# -# edit this to suit your needs (here with sampleuser idfx) -# After you edited this file, build.sh has to be invoked. -# To be sure, also restart Tomcat. -# -# Note that for Mir to work, Tomcat has to be set up to handle all -# URLs that begin with /servlet. All other URLs are handled by Apache. -# -# The setup uses the following assumptions: -# The URL to reach the site is http://indy.code-fu.de -# The StorageRoot of this URL is /pub/Dokumente/Indymedia/de-tech/Mir -# All data is located below this directory, including the servlets. - - -# -# # GENERAL SETUP # @@ -43,7 +12,7 @@ Mir.Tech-email.name=mir-coders mailinglist Mir.Public-email.address=mir-coders@lists.indymedia.org Mir.Public-email.name=mir-coders mailinglist -Mir.Version=1.1beta +Mir.Version=1.1.0rc0 DirectOpenposting=yes # The name of the abuse config file (relative to the WEB-INF dir) @@ -61,7 +30,7 @@ Abuse.CookieMaxAge=168 #where to put the lucene index -IndexPath=/tmp/index +IndexPath=index TempDir=/tmp @@ -85,57 +54,80 @@ Mir.Login.Languages=en;de;fr;nl;es;pt;eu;sv;tr;zh;gz # For missing values, the FallbackLanguage is used as default Mir.Admin.FallbackLanguage=en +# Show who's logged in? +Mir.Admin.ShowLoggedinUsers=1 + +# Log admin activity? +Mir.Admin.LogAdminActivity=0 + +# Limit the length of text shown in lists (-1 means no limit) +Mir.Admin.ListTextLengthLimit=-1 # Which usernames have admin priviliges (, seperated usernames) AccessControl.SuperUsers = admin +# Locking enabled? +AccessControl.LockingEnabled = 0 + +# If locking enabled, should users lock articles before they +# can edit? +AccessControl.LockingOptional = 1 + # the templates Mir.Localizer.Producer.GeneratorLibrary= default=freemarker(etc/producer/) -Mir.Localizer.Admin.GeneratorLibrary= default=freemarker(templates/admin/) +Mir.Localizer.Admin.GeneratorLibrary= default=freemarker(templates/admin/),preview=freemarker(etc/producer) Mir.Localizer.OpenPosting.GeneratorLibrary= default=freemarker(etc/open/) # How should the custom operations (hide etc) in article and comment lists # be presented? # 0 = links, 1 = checkboxes, 2 = a listbox Mir.Localizer.Admin.ListOperationsFlavor=1 + +# Article previews, a comma seperated list of name = generator +Mir.Localizer.Admin.ArticlePreview = \ + default = preview::article.template +Mir.Localizer.Admin.ArticlePreviewLanguage=en # How should the topics be presented on the article edit page? -# 0 = in a multiselect list box, 1 = checkboxes -Mir.Localizer.Admin.TopicListFlavor=1 - -# For the checkboxes flavour, how many columns should there be? -Mir.Localizer.Admin.TopicListColumns=3 +# +# :::: +# multiple entries can be specified, can be seperated by a , +# +# key: +# the bundle key to use for the field label +# listtype: +# 0 = in a multiselect list box, 1 = checkboxes, 2 = a dropdown listbox +# listparameter: +# number of rows for multiselect list box, number of columns for checkboxes +# condition: +# what sql condition should the topics of this category be of +# order: +# what sql order should the topics be ordered by -# In which order should the topic appear? -Mir.Localizer.Admin.TopicListOrder=title +Mir.Localizer.Admin.TopicLists = \ + content.topic:1:3::title # enable deletion of comments/articles? Mir.Localizer.Admin.AllowDeleteComment=1 Mir.Localizer.Admin.AllowDeleteArticle=1 # Article Preview Link URL (Link to produced articles from within admin) -ContentList.ArticleLink=http://production.indy.code-foo.org/en/${date.formatted.yyyy}/${date.formatted.MM}/${id}.shtml -CommentList.ArticleLink=http://production.indy.code-foo.org/en/${co_content.date.formatted.yyyy}/${to_content.date.formatted.MM}/${to_content.id}.shtml +Comment.PublicUrl=/en/${date.formatted.yyyy}/${date.formatted.MM}/${id}.shtml +Article.PublicUrl=/en/${to_content.date.formatted.yyyy}/${to_content.date.formatted.MM}/${to_content.id}.shtml -# enable deletion of comments/articles? +# which 'quick' operations should be available in the top-left box? Mir.Localizer.Admin.AdministerOperations= \ comments:module=Comment&do=list - # Which producers need to be called after an article (resp. a comment) is posted Mir.Localizer.OpenPosting.ContentProducers= media.new;articles.changed;startpage.generate;synchronization.run Mir.Localizer.OpenPosting.CommentProducers= articles.changed;synchronization.run # Which producers need to be called after the "produce all new" link is clicked from admin -Mir.Localizer.Producer.AllNewProducers= media.new;articles.changed;startpage.run;synchronization.run +Mir.Localizer.Producer.ProducerRecipes= \ + allnew = media.new;articles.changed;startpage.run;synchronization.run -#note that you can't make pdf's without making fo's -#this is actually now set in producers.xml -#but these summarize what is said in there for the benefit of OpenMir -GenerateFO=yes -GeneratePDF=yes - #use rsync to mirror the website to a remote-host Rsync=no Rsync.Script.Path=/var/www/bin/rsync-copy @@ -167,7 +159,7 @@ Producer.StorageRoot=/pub/Dokumente/Indymedia/de-tech/Mir/produced # FileEdit module # a list of directories to edit -# format: +# format: # :::<0|1 (recursion off or on)> [, ....] ServletModule.FileEdit.Configuration= \ @@ -257,11 +249,11 @@ Producer.Icon.BigText=text_big.gif Producer.HTML2FOStyleSheet=/some/dir/mir/etc/producer/html2fo.xsl # the following lines are used to construct PDFs on the fly from one or more articles -# for the moment, if you want to change anything else about your pdfs, you +# for the moment, if you want to change anything else about your pdfs, you # will have to learn some java! # -# keep in mind that there may not be enough room for all the text you enter as the -# value of one these options, if text doesn't appear, the only easy thing to do is +# keep in mind that there may not be enough room for all the text you enter as the +# value of one these options, if text doesn't appear, the only easy thing to do is # use less text! # # also, be sure to adjust the corresponding line height if you change a font size... @@ -287,12 +279,12 @@ PDF.Title.FontSize=24 PDF.Title.LineHeight=28 PDF.Title.FontFamily=courier -# footer is about two lines of small text which will appear at the bottom of every page +# footer is about two lines of small text which will appear at the bottom of every page PDF.Footer.String=Indymedia does blah. Content is good, and free to use for non-commercial purposes under the Open Content license. if you have questions, email someone. PDF.Footer.Height=54 PDF.Footer.FontSize=12 -PDF.Footer.FontFamily=helvetica +PDF.Footer.FontFamily=helvetica # how to format the index, i.e. the newsletter table of contents @@ -304,7 +296,7 @@ PDF.Index.FontFamily=helvetica PDF.Meta.Height=36 PDF.Meta.FontSize=14 -PDF.Meta.FontFamily=helvetica +PDF.Meta.FontFamily=helvetica RDF.Meta.DateFormat=yyyy-MM-dd HH:mm # how to format the article description @@ -352,9 +344,6 @@ Global.Cache.Items=15 # DATABASE SETUP # -# -# specify your database - Database.poolMin=1 Database.poolMax=10 Database.poolResetTime=1.0 @@ -384,28 +373,47 @@ Mir.DefaultEncoding=UTF8 Mir.DefaultHTMLCharset=UTF-8 # Default timezone to display times in in admin, producers -# -# Leave empty to use the system's default -Mir.DefaultTimezone= +Mir.DefaultTimezone= UTC # Default date/time format Mir.DefaultDateTimeFormat = yyyy-MM-dd HH:mm +# Compatibility feature: updated posting forms can +# support persistent uploads (that is, uploads remainig +# valid after validation errors). To support existing +# forms, by default it is off. +Localizer.OpenSession.PersistentUploadedFiles = 0 +# Should support for ftp-like uploads (uploads done +# outside of mir, but included into postings) be +# supported at all? +Localizer.OpenSession.AllowFTPUploads = 0 +# When uploading ftp files, should a list of available +# files be displayed? +Localizer.OpenSession.AllowFTPUploadSelection = 0 + +# What is the place where files are uploaded? +Localizer.OpenSession.FTPDirectory = /somewhere Localizer.OpenSession.article.EditTemplate = editarticle.template Localizer.OpenSession.article.DupeTemplate = dupearticle.template Localizer.OpenSession.article.DoneTemplate = donearticle.template Localizer.OpenSession.article.UnsupportedMediaTemplate = unsupportedmediatype.template Localizer.OpenSession.article.DefaultArticleType=newswire +Localizer.OpenSession.article.DefaultMediaFolder=openposting Localizer.OpenSession.comment.EditTemplate = editcomment.template Localizer.OpenSession.comment.DupeTemplate = dupecomment.template Localizer.OpenSession.comment.DoneTemplate = donecomment.template Localizer.OpenSession.comment.UnsupportedMediaTemplate = unsupportedmediatype.template +Localizer.OpenSession.comment.DefaultCommentStatus=normal +Localizer.OpenSession.comment.DefaultMediaFolder=openposting Localizer.OpenSession.ErrorTemplate = sessionerror.template +Localizer.OpenSession.email.PrepareTemplate = preparemail.template +Localizer.OpenSession.email.MailTemplate = email_article.template +Localizer.OpenSession.email.DoneTemplate =/sent_mail.template @@ -502,16 +510,32 @@ ServletModule.CommentStatus.DeleteConfirmationTemplate=confirm.template ServletModule.CommentStatus.EditTemplate=commentstatus.template ServletModule.CommentStatus.ListTemplate=commentstatuslist.template +ServletModule.MediaType.DeleteConfirmationTemplate=confirm.template +ServletModule.MediaType.EditTemplate=mediatype.template +ServletModule.MediaType.ListTemplate=mediatypelist.template + +# +# Object store configuration +# + +StoreContainer.EntityDefaultSize= 45 +StoreContainer.EntityListDefaultSize= 15 +StorableObjectEntity.Entity.DefaultSize= 300 +StorableObjectEntity.EntityList.DefaultSize= 100 +EntityTopics.Entity.DefaultSize= 200 +EntityTopics.EntityList.DefaultSize= 20 + + # # config for abuse -ServletModule.Abuse.EditFilter.Template = abuse.filter.template -ServletModule.Abuse.ListFilters.Template = abuse.filters.template -ServletModule.Abuse.ViewLog.Template = abuse.log.template -ServletModule.Abuse.Main.Template = abuse.template +ServletModule.Abuse.EditFilter.Template = abuse.filter.template +ServletModule.Abuse.ListFilters.Template = abuse.filters.template +ServletModule.Abuse.ViewLog.Template = abuse.log.template +ServletModule.Abuse.Main.Template = abuse.template # # producer-related configs below @@ -521,8 +545,6 @@ Producer.ExtLinkName=extlink.gif Producer.IntLinkName=intlink.gif Producer.MailLinkName=maillink.gif -#objectstore -StoreContainer.EntityDefaultSize=45 -StoreContainer.EntityListDefaultSize=15 -StorableObjectEntity.Entity.DefaultSize=5000 -StorableObjectEntity.EntityList.DefaultSize=400 +# should the + + + + + + + jdbc:postgresql://127.0.0.1:5432/mir3 + + + org.postgresql.Driver + + mir + + + net.sf.hibernate.dialect.PostgreSQLDialect + + true + false + + + + 0 + 8 + 8 + 0 + -1 + + + + + + + + + + + + + + + + + + + + diff --git a/source/mircoders/servlet/ServletHelper.java b/source/mircoders/servlet/ServletHelper.java index 5ed322ca..1fa09018 100755 --- a/source/mircoders/servlet/ServletHelper.java +++ b/source/mircoders/servlet/ServletHelper.java @@ -30,32 +30,29 @@ package mircoders.servlet; import java.io.PrintWriter; -import java.util.HashMap; +import java.io.IOException; 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.entity.adapter.EntityAdapter; import mir.generator.Generator; +import mir.generator.GeneratorHelper; 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"); - + private 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"); + return makeGenerationData(aRequest, aResponse, aLocales, "etc/bundles/adminlocal", "bundles/admin"); } public static Map makeGenerationData(HttpServletRequest aRequest, HttpServletResponse aResponse, Locale[] aLocales, String aBundle) throws ServletModuleExc { @@ -63,11 +60,16 @@ public class ServletHelper { } 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); + MirPropertiesConfiguration configuration = MirPropertiesConfiguration.instance(); + Map result = GeneratorHelper.makeBasicGenerationData(aLocales, aBundle, aDefaultBundle); + if (configuration.getString("Mir.Admin.ShowLoggedinUsers").equals("1")) { + result.put("loggedinusers", MirGlobal.getLoggedInUsers()); + } + else { + result.put("loggedinusers", null); + } + result.put("systemstatus", MirGlobal.getStatus()); // ML: hackish ((Map) result.get("config")).put("actionRoot", @@ -76,36 +78,6 @@ public class ServletHelper { 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) { @@ -141,11 +113,26 @@ public class ServletHelper { } } + public static void generateInfoMessage(HttpServletRequest aRequest, HttpServletResponse aResponse, + Locale[] aLocales, String aBundle, String aDefaultBundle, String aMessage, String anArgument1, String anArgument2) throws ServletModuleExc { + Map responseData = makeGenerationData(aRequest, aResponse, aLocales, aBundle, aDefaultBundle); + responseData.put("message", aMessage); + responseData.put("argument1", anArgument1); + responseData.put("argument2", anArgument2); + + try { + generateResponse(aResponse.getWriter(), responseData, "infomessage.template"); + } + catch (IOException e) { + throw new ServletModuleFailure(e); + } + } + 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) { + catch (IOException t) { throw new ServletModuleFailure("ServletModule.redirect: " +t.getMessage(), t); } } @@ -178,7 +165,7 @@ public class ServletHelper { EntityUsers user = getUser(aRequest); if (user!=null) - return user.getValue("login"); + return user.getFieldValue("login"); else return "nobody"; } diff --git a/source/mircoders/servlet/ServletModuleAbuse.java b/source/mircoders/servlet/ServletModuleAbuse.java index 6c0fb939..e026be60 100755 --- a/source/mircoders/servlet/ServletModuleAbuse.java +++ b/source/mircoders/servlet/ServletModuleAbuse.java @@ -1,245 +1,296 @@ -/* - * 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.ServletModuleExc; -import mir.servlet.ServletModuleFailure; -import mir.util.HTTPRequestParser; -import mir.util.URLBuilder; -import mircoders.global.Abuse; -import mircoders.global.MirGlobal; - -public class ServletModuleAbuse extends ServletModule { - private static ServletModuleAbuse instance = new ServletModuleAbuse(); - private String editFilterTemplate; - private String listFiltersTemplate; - private String mainTemplate; - private String viewLogTemplate; - - public static ServletModule getInstance() { return instance; } - - private ServletModuleAbuse() { - logger = new LoggerWrapper("ServletModule.Abuse"); - defaultAction = "showsettings"; - - editFilterTemplate = configuration.getString("ServletModule.Abuse.EditFilter.Template"); - listFiltersTemplate = configuration.getString("ServletModule.Abuse.ListFilters.Template"); - viewLogTemplate = configuration.getString("ServletModule.Abuse.ViewLog.Template"); - mainTemplate = configuration.getString("ServletModule.Abuse.Main.Template"); - } - - public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - String id=requestParser.getParameterWithDefault("id", ""); - - if (id.equals("")) { - editfilter(aRequest, aResponse, "", "", "", "", "", "", ""); - } - else { - Abuse.FilterRule filter = MirGlobal.abuse().getFilter(id); - if (filter==null) - throw new ServletModuleExc("Filter not found"); - - editfilter(aRequest, aResponse, filter.getId(), filter.getType(), filter.getExpression(), filter.getComments(), filter.getCommentAction(), filter.getArticleAction(), ""); - } - } - - public void editfilter(HttpServletRequest aRequest, HttpServletResponse aResponse, - String anId, String aType, String anExpression, String aComments, - String aCommentAction, String anArticleAction, String anErrorMessage) throws ServletModuleExc { - try { - Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}); - - responseData.put("id", anId); - responseData.put("type", aType); - responseData.put("expression", anExpression); - responseData.put("comments", aComments); - responseData.put("articleaction", anArticleAction); - responseData.put("commentaction", aCommentAction); - responseData.put("errormessage", anErrorMessage); - - responseData.put("articleactions", MirGlobal.abuse().getArticleActions()); - responseData.put("commentactions", MirGlobal.abuse().getCommentActions()); - responseData.put("filtertypes", MirGlobal.abuse().getFilterTypes()); - - ServletHelper.generateResponse(aResponse.getWriter(), responseData, editFilterTemplate); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - public void updatefilter(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - - String type=requestParser.getParameterWithDefault("type", ""); - String id=requestParser.getParameterWithDefault("id", ""); - String expression=requestParser.getParameterWithDefault("expression", ""); - String commentaction=requestParser.getParameterWithDefault("commentaction", ""); - String articleaction=requestParser.getParameterWithDefault("articleaction", ""); - String comments=requestParser.getParameterWithDefault("comments", ""); - - String errorMessage; - - String userName = ServletHelper.getUserName(aRequest); - - if (id.equals("")) { - errorMessage = MirGlobal.abuse().addFilter(type, expression,comments, commentaction, articleaction); - } - else { - errorMessage = MirGlobal.abuse().setFilter(id, type, expression, comments, commentaction, articleaction); - } - - if (errorMessage!=null) { - editfilter(aRequest, aResponse, id, type, expression, comments, commentaction, articleaction, errorMessage); - } - else { - MirGlobal.abuse().save(); - showfilters(aRequest, aResponse); - } - } - - public void delete(HttpServletRequest aRequest, HttpServletResponse aResponse) { - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - - String id=requestParser.getParameterWithDefault("id", ""); - MirGlobal.abuse().deleteFilter(id); - - MirGlobal.abuse().save(); - - showfilters(aRequest, aResponse); - } - - public void add(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { - editfilter(aRequest, aResponse, "", "", "", "", "", "", ""); - } - public void showfilters(HttpServletRequest aRequest, HttpServletResponse aResponse) { - URLBuilder urlBuilder = new URLBuilder(); - - try { - Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}); - - urlBuilder.setValue("module", "Abuse"); - urlBuilder.setValue("do", "showfilters"); - responseData.put("thisurl", urlBuilder.getQuery()); - - responseData.put("filters", MirGlobal.abuse().getFilters()); - - ServletHelper.generateResponse(aResponse.getWriter(), responseData, listFiltersTemplate); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - public void showsettings(HttpServletRequest aRequest, HttpServletResponse aResponse) { - URLBuilder urlBuilder = new URLBuilder(); - - try { - Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}); - - urlBuilder.setValue("module", "Abuse"); - urlBuilder.setValue("do", "showsettings"); - - responseData.put("thisurl", urlBuilder.getQuery()); - - responseData.put("articleactions", MirGlobal.abuse().getArticleActions()); - responseData.put("commentactions", MirGlobal.abuse().getCommentActions()); - - responseData.put("disableop", new Boolean(MirGlobal.abuse().getOpenPostingDisabled())); - responseData.put("passwordop", new Boolean(MirGlobal.abuse().getOpenPostingPassword())); - responseData.put("logenabled", new Boolean(MirGlobal.abuse().getLogEnabled())); - responseData.put("logsize", Integer.toString(MirGlobal.abuse().getLogSize())); - responseData.put("usecookies", new Boolean(MirGlobal.abuse().getCookieOnBlock())); - responseData.put("articleaction", MirGlobal.abuse().getArticleBlockAction()); - responseData.put("commentaction", MirGlobal.abuse().getCommentBlockAction()); - - ServletHelper.generateResponse(aResponse.getWriter(), responseData, mainTemplate); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - public void savesettings(HttpServletRequest aRequest, HttpServletResponse aResponse) { - try { - HTTPRequestParser parser = new HTTPRequestParser(aRequest); - - MirGlobal.abuse().setOpenPostingDisabled(parser.getParameterWithDefault("disableop", "").equals("1")); - MirGlobal.abuse().setOpenPostingPassword(parser.getParameterWithDefault("passwordop", "").equals("1")); - MirGlobal.abuse().setLogEnabled(parser.getParameterWithDefault("logenabled", "").equals("1")); - - try { - MirGlobal.abuse().setLogSize(parser.getIntegerWithDefault("logsize", MirGlobal.abuse().getLogSize())); - } - catch (Throwable t) { - } - - MirGlobal.abuse().setCookieOnBlock(parser.getParameterWithDefault("usecookies", "").equals("1")); - - MirGlobal.abuse().setArticleBlockAction(parser.getParameter("articleaction")); - MirGlobal.abuse().setCommentBlockAction(parser.getParameter("commentaction")); - - MirGlobal.abuse().save(); - - showsettings(aRequest, aResponse); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - public void showlog(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", "Abuse"); - urlBuilder.setValue("do", "showlog"); - responseData.put("thisurl", urlBuilder.getQuery()); - - responseData.put("log", MirGlobal.abuse().getLog()); - - ServletHelper.generateResponse(aResponse.getWriter(), responseData, viewLogTemplate); - } - 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.log.LoggerWrapper; +import mir.servlet.ServletModule; +import mir.servlet.ServletModuleExc; +import mir.servlet.ServletModuleFailure; +import mir.util.HTTPRequestParser; +import mir.util.URLBuilder; +import mircoders.global.Abuse; +import mircoders.global.MirGlobal; + +public class ServletModuleAbuse extends ServletModule { + private static ServletModuleAbuse instance = new ServletModuleAbuse(); + private String editFilterTemplate; + private String listFiltersTemplate; + private String mainTemplate; + private String viewLogTemplate; + + public static ServletModule getInstance() { return instance; } + + private ServletModuleAbuse() { + logger = new LoggerWrapper("ServletModule.Abuse"); + defaultAction = "showsettings"; + + editFilterTemplate = configuration.getString("ServletModule.Abuse.EditFilter.Template"); + listFiltersTemplate = configuration.getString("ServletModule.Abuse.ListFilters.Template"); + viewLogTemplate = configuration.getString("ServletModule.Abuse.ViewLog.Template"); + mainTemplate = configuration.getString("ServletModule.Abuse.Main.Template"); + } + + public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + String id=requestParser.getParameterWithDefault("id", ""); + + if (id.equals("")) { + editfilter(aRequest, aResponse, "", "", "", "", "", "", ""); + } + else { + Abuse.FilterRule filter = MirGlobal.abuse().getFilter(id); + if (filter==null) + throw new ServletModuleExc("Filter not found"); + + editfilter(aRequest, aResponse, filter.getId(), filter.getType(), filter.getExpression(), filter.getComments(), filter.getCommentAction(), filter.getArticleAction(), ""); + } + } + + public void editfilter(HttpServletRequest aRequest, HttpServletResponse aResponse, + String anId, String aType, String anExpression, String aComments, + String aCommentAction, String anArticleAction, String anErrorMessage) throws ServletModuleExc { + try { + Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, getLocales(aRequest)); + + responseData.put("id", anId); + responseData.put("type", aType); + responseData.put("expression", anExpression); + responseData.put("comments", aComments); + responseData.put("articleaction", anArticleAction); + responseData.put("commentaction", aCommentAction); + responseData.put("errormessage", anErrorMessage); + + responseData.put("articleactions", MirGlobal.abuse().getArticleActions()); + responseData.put("commentactions", MirGlobal.abuse().getCommentActions()); + responseData.put("filtertypes", MirGlobal.abuse().getFilterTypes()); + + ServletHelper.generateResponse(aResponse.getWriter(), responseData, editFilterTemplate); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + public void updatefilter(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + + String type=requestParser.getParameterWithDefault("type", ""); + String id=requestParser.getParameterWithDefault("id", ""); + String expression=requestParser.getParameterWithDefault("expression", ""); + String commentaction=requestParser.getParameterWithDefault("commentaction", ""); + String articleaction=requestParser.getParameterWithDefault("articleaction", ""); + String comments=requestParser.getParameterWithDefault("comments", ""); + + String errorMessage; + + if (id.equals("")) { + errorMessage = MirGlobal.abuse().addFilter(type, expression,comments, commentaction, articleaction); + logAdminUsage(aRequest, "?", "object added"); + } + else { + errorMessage = MirGlobal.abuse().setFilter(id, type, expression, comments, commentaction, articleaction); + logAdminUsage(aRequest, id, "object modified"); + } + + if (errorMessage!=null) { + editfilter(aRequest, aResponse, id, type, expression, comments, commentaction, articleaction, errorMessage); + } + else { + MirGlobal.abuse().save(); + showfilters(aRequest, aResponse); + } + } + + public void delete(HttpServletRequest aRequest, HttpServletResponse aResponse) { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + + String id=requestParser.getParameterWithDefault("id", ""); + MirGlobal.abuse().deleteFilter(id); + logAdminUsage(aRequest, id, "object deleted"); + + MirGlobal.abuse().save(); + + showfilters(aRequest, aResponse); + } + + public void moveup(HttpServletRequest aRequest, HttpServletResponse aResponse) { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + + String id=requestParser.getParameterWithDefault("id", ""); + MirGlobal.abuse().moveFilterUp(id); + + MirGlobal.abuse().save(); + logAdminUsage(aRequest, id, "object moved upwards"); + + showfilters(aRequest, aResponse); + } + + public void movedown(HttpServletRequest aRequest, HttpServletResponse aResponse) { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + + String id=requestParser.getParameterWithDefault("id", ""); + MirGlobal.abuse().moveFilterDown(id); + logAdminUsage(aRequest, id, "object moved downwards"); + + MirGlobal.abuse().save(); + + showfilters(aRequest, aResponse); + } + + public void movetop(HttpServletRequest aRequest, HttpServletResponse aResponse) { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + + String id=requestParser.getParameterWithDefault("id", ""); + MirGlobal.abuse().moveFilterToTop(id); + + MirGlobal.abuse().save(); + logAdminUsage(aRequest, id, "object moved to the top"); + + showfilters(aRequest, aResponse); + } + + public void movebottom(HttpServletRequest aRequest, HttpServletResponse aResponse) { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + + String id=requestParser.getParameterWithDefault("id", ""); + MirGlobal.abuse().moveFilterToBottom(id); + + MirGlobal.abuse().save(); + logAdminUsage(aRequest, id, "object moved to the bottom"); + + showfilters(aRequest, aResponse); + } + + public void add(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { + editfilter(aRequest, aResponse, "", "", "", "", "", "", ""); + } + + public void showfilters(HttpServletRequest aRequest, HttpServletResponse aResponse) { + URLBuilder urlBuilder = new URLBuilder(); + + try { + Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, getLocales(aRequest)); + + urlBuilder.setValue("module", "Abuse"); + urlBuilder.setValue("do", "showfilters"); + responseData.put("thisurl", urlBuilder.getQuery()); + + responseData.put("filters", MirGlobal.abuse().getFilters()); + + ServletHelper.generateResponse(aResponse.getWriter(), responseData, listFiltersTemplate); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + public void showsettings(HttpServletRequest aRequest, HttpServletResponse aResponse) { + URLBuilder urlBuilder = new URLBuilder(); + + try { + Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, getLocales(aRequest)); + + urlBuilder.setValue("module", "Abuse"); + urlBuilder.setValue("do", "showsettings"); + + responseData.put("thisurl", urlBuilder.getQuery()); + + responseData.put("articleactions", MirGlobal.abuse().getArticleActions()); + responseData.put("commentactions", MirGlobal.abuse().getCommentActions()); + + responseData.put("disableop", new Boolean(MirGlobal.abuse().getOpenPostingDisabled())); + responseData.put("passwordop", new Boolean(MirGlobal.abuse().getOpenPostingPassword())); + responseData.put("logenabled", new Boolean(MirGlobal.abuse().getLogEnabled())); + responseData.put("logsize", Integer.toString(MirGlobal.abuse().getLogSize())); + responseData.put("usecookies", new Boolean(MirGlobal.abuse().getCookieOnBlock())); + responseData.put("articleaction", MirGlobal.abuse().getArticleBlockAction()); + responseData.put("commentaction", MirGlobal.abuse().getCommentBlockAction()); + + ServletHelper.generateResponse(aResponse.getWriter(), responseData, mainTemplate); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + public void savesettings(HttpServletRequest aRequest, HttpServletResponse aResponse) { + try { + HTTPRequestParser parser = new HTTPRequestParser(aRequest); + + MirGlobal.abuse().setOpenPostingDisabled(parser.getParameterWithDefault("disableop", "").equals("1")); + MirGlobal.abuse().setOpenPostingPassword(parser.getParameterWithDefault("passwordop", "").equals("1")); + MirGlobal.abuse().setLogEnabled(parser.getParameterWithDefault("logenabled", "").equals("1")); + + try { + MirGlobal.abuse().setLogSize(parser.getIntegerWithDefault("logsize", MirGlobal.abuse().getLogSize())); + } + catch (Throwable t) { + } + + MirGlobal.abuse().setCookieOnBlock(parser.getParameterWithDefault("usecookies", "").equals("1")); + + MirGlobal.abuse().setArticleBlockAction(parser.getParameter("articleaction")); + MirGlobal.abuse().setCommentBlockAction(parser.getParameter("commentaction")); + + MirGlobal.abuse().save(); + logAdminUsage(aRequest, "settings", "object modified"); + + showsettings(aRequest, aResponse); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + public void showlog(HttpServletRequest aRequest, HttpServletResponse aResponse) { + URLBuilder urlBuilder = new URLBuilder(); + + try { + Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, getLocales(aRequest)); + urlBuilder.setValue("module", "Abuse"); + urlBuilder.setValue("do", "showlog"); + responseData.put("thisurl", urlBuilder.getQuery()); + + responseData.put("log", MirGlobal.abuse().getLog()); + + ServletHelper.generateResponse(aResponse.getWriter(), responseData, viewLogTemplate); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } } \ No newline at end of file diff --git a/source/mircoders/servlet/ServletModuleAdmin.java b/source/mircoders/servlet/ServletModuleAdmin.java index ec85a080..568983bf 100755 --- a/source/mircoders/servlet/ServletModuleAdmin.java +++ b/source/mircoders/servlet/ServletModuleAdmin.java @@ -1,102 +1,145 @@ -/* - * 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); - } - } - -} +/* + * 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.IOException; +import java.io.Writer; +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.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(); + + try { + Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, getLocales(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); + } + } + + /** + * Servlet handler method to reload the configuration for scripts. + * The output will be aimed at shell sripts. + */ + public void reload(HttpServletRequest aRequest, HttpServletResponse aResponse) { + String result = "reload successfull"; + + try { + MirGlobal.reloadConfigurations(); + } + catch (Throwable t) { + result = "error occurred while reloading: " +t.toString(); + } + + try { + Writer writer = aResponse.getWriter(); + writer.write(result); + } + catch (IOException e) { + throw new ServletModuleFailure(e); + } + } + + /** + * Servlet handler method to reload the configuration. + */ + public void reloadconfiguration(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { + try { + MirGlobal.reloadConfigurations(); + ServletHelper.generateInfoMessage(aRequest, aResponse, getLocales(aRequest), + "bundles/admin", "etc/bundles/adminlocal", "reloadSuccessfull", "", ""); + } + catch (Throwable t) { + ServletHelper.generateInfoMessage(aRequest, aResponse, getLocales(aRequest), + "bundles/admin", "etc/bundles/adminlocal", "reloadFailed", t.toString(), ""); + } + } + + public void start(HttpServletRequest aRequest, HttpServletResponse aResponse) { + String defaultStartTemplate = configuration.getString("Mir.StartTemplate"); + + try { + Map mergeData = ServletHelper.makeGenerationData(aRequest, aResponse, getLocales(aRequest), + "bundles/admin", "etc/bundles/adminlocal"); + mergeData.put("messages", + new CachingRewindableIterator( + new EntityIteratorAdapter("", "webdb_create desc", 10, + MirGlobal.localizer().dataModel().adapterModel(), "internalMessage", 10, 0))); + + mergeData.put("fileeditentries", ( (ServletModuleFileEdit) ServletModuleFileEdit.getInstance()).getEntries()); + mergeData.put("administeroperations", ( (ServletModuleLocalizer) ServletModuleLocalizer.getInstance()).getAdministerOperations()); + + mergeData.put("searchvalue", null); + mergeData.put("searchfield", null); + mergeData.put("searchispublished", null); + mergeData.put("searcharticletype", null); + mergeData.put("searchorder", null); + mergeData.put("selectarticleurl", null); + mergeData.put("recipes", MirGlobal.localizer().producers().getRecipeNames()); + + String startTemplate = MirGlobal.localizer().adminInterface().getAdminPageGenerator( + "admin.start", mergeData, + ServletHelper.getUserAdapter(aRequest), defaultStartTemplate); + + 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 63de8b3c..1a99da2a 100755 --- a/source/mircoders/servlet/ServletModuleArticleType.java +++ b/source/mircoders/servlet/ServletModuleArticleType.java @@ -1,64 +1,61 @@ -/* - * 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()); - } - } -} +/* + * 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.module.ModuleArticleType; + +/** + * + *

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 { + definition = "articleType"; + mainModule = new ModuleArticleType(); + } + 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 a35f1772..e57cbe79 100755 --- a/source/mircoders/servlet/ServletModuleAudio.java +++ b/source/mircoders/servlet/ServletModuleAudio.java @@ -29,12 +29,11 @@ */ package mircoders.servlet; -import mir.config.MirPropertiesConfiguration; import mir.log.LoggerWrapper; import mir.servlet.ServletModule; +import mircoders.global.MirGlobal; import mircoders.module.ModuleUploadedMedia; import mircoders.storage.DatabaseAudio; -import mircoders.global.*; /* * @@ -55,7 +54,6 @@ public class ServletModuleAudio extends ServletModuleUploadedMedia { moduleName = "Audio"; try { - model = MirGlobal.localizer().dataModel().adapterModel(); definition = "audio"; mainModule = new ModuleUploadedMedia(DatabaseAudio.getInstance()); } diff --git a/source/mircoders/servlet/ServletModuleBreaking.java b/source/mircoders/servlet/ServletModuleBreaking.java index ca659814..dd4ea8d3 100755 --- a/source/mircoders/servlet/ServletModuleBreaking.java +++ b/source/mircoders/servlet/ServletModuleBreaking.java @@ -1,66 +1,65 @@ -/* - * 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()); - } - } -} +/* + * 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 { + definition = "breakingNews"; + mainModule = new ModuleBreaking(); + } + 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 251c37cb..8d82c448 100755 --- a/source/mircoders/servlet/ServletModuleComment.java +++ b/source/mircoders/servlet/ServletModuleComment.java @@ -1,355 +1,342 @@ -/* - * 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; -import java.util.Locale; -import java.util.Map; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import mir.config.MirPropertiesConfiguration; -import mir.entity.adapter.EntityAdapterModel; -import mir.entity.adapter.EntityIteratorAdapter; -import mir.log.LoggerWrapper; -import mir.servlet.ServletModule; -import mir.servlet.ServletModuleExc; -import mir.servlet.ServletModuleFailure; -import mir.servlet.ServletModuleUserExc; -import mir.util.CachingRewindableIterator; -import mir.util.HTTPRequestParser; -import mir.util.JDBCStringRoutines; -import mir.util.SQLQueryBuilder; -import mir.util.URLBuilder; -import mircoders.entity.EntityComment; -import mircoders.global.MirGlobal; -import mircoders.module.ModuleComment; -import mircoders.module.ModuleContent; -import mircoders.storage.DatabaseComment; -import mircoders.storage.DatabaseContent; - -/* - * ServletModuleComment - controls navigation for Comments - * - * - * @author the mir-coders - */ - -public class ServletModuleComment extends ServletModule -{ - private ModuleContent moduleContent; - - private static ServletModuleComment instance = new ServletModuleComment(); - public static ServletModule getInstance() { return instance; } - - private ServletModuleComment() { - logger = new LoggerWrapper("ServletModule.Comment"); - try { - mainModule = new ModuleComment(DatabaseComment.getInstance()); - moduleContent = new ModuleContent(DatabaseContent.getInstance()); - } - catch (Exception e) { - logger.error("servletmodule comment could not be initialized:" + e.getMessage()); - } - } - - public void delete(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { - try { - MirGlobal.accessControl().general().assertMayDeleteComments(ServletHelper.getUser(aRequest)); - - super.delete(aRequest, aResponse); - } - catch (Throwable t) { - throw new ServletModuleFailure(t); - } - } - - public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { - String idParam = aRequest.getParameter("id"); - - if (idParam == null) - throw new ServletModuleExc("Invalid call: id not supplied "); - - showComment(idParam, aRequest, aResponse); - } - - public void showComment(String anId, 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 comment; - URLBuilder urlBuilder = new URLBuilder(); - - urlBuilder.setValue("module", "Comment"); - urlBuilder.setValue("do", "edit"); - urlBuilder.setValue("id", anId); - urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl")); - - if (anId != null) { - responseData.put("new", Boolean.FALSE); - comment = model.makeEntityAdapter("comment", mainModule.getById(anId)); - } - else { - List fields = DatabaseComment.getInstance().getFields(); - responseData.put("new", Boolean.TRUE); - comment = new HashMap(); - Iterator i = fields.iterator(); - while (i.hasNext()) { - comment.put(i.next(), null); - } - } - responseData.put("comment", comment); - - 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 attach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { - String mediaIdParam = aRequest.getParameter("mid"); - String commentId = aRequest.getParameter("commentid"); - - if (commentId == null || mediaIdParam==null) throw new ServletModuleExc("smod comment :: attach :: commentid/mid missing"); - - try { - EntityComment comment = (EntityComment) mainModule.getById(commentId); - comment.attach(mediaIdParam); - } - catch(Throwable e) { - throw new ServletModuleFailure(e); - } - - showComment(commentId, aRequest, aResponse); - } - - public void dettach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { - String commentId = aRequest.getParameter("commentid"); - String midParam = aRequest.getParameter("mid"); - if (commentId == null) - throw new ServletModuleExc("smod comment :: dettach :: commentid missing"); - if (midParam == null) - throw new ServletModuleExc("smod comment :: dettach :: mid missing"); - - try { - EntityComment comment = (EntityComment)mainModule.getById(commentId); - comment.dettach(commentId, midParam); - } - catch(Throwable e) { - throw new ServletModuleFailure(e); - } - - showComment(commentId, aRequest, aResponse); - } - - - public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - - String where = requestParser.getParameter("where"); - String order = requestParser.getParameterWithDefault("order", "webdb_create desc"); - int offset = requestParser.getIntegerWithDefault("offset", 0); - - returnCommentList(aRequest, aResponse, where, order, offset); - } - - public void search(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - SQLQueryBuilder queryBuilder = new SQLQueryBuilder(); - - String queryField = ""; - String searchField = requestParser.getParameter("searchfield"); - String searchText = requestParser.getParameter("searchtext"); - String searchIsPublished = requestParser.getParameter("searchispublished"); - String searchStatus = requestParser.getParameter("searchstatus"); - String searchOrder = requestParser.getParameter("searchorder"); - - if (searchIsPublished.equals("0")) { - queryBuilder.appendAndCondition("is_published='f'"); - } - else if (searchIsPublished.equals("1")) { - queryBuilder.appendAndCondition("is_published='t'"); - } - - if (searchText.length()>0) { - queryBuilder.appendAndCondition( - "lower("+ searchField + ") like " + - "'%" + JDBCStringRoutines.escapeStringLiteral(searchText.toLowerCase()) + "%'"); - } - - if (searchStatus.length()>0) { - queryBuilder.appendAndCondition("to_comment_status="+Integer.parseInt(searchStatus)); - } - - if (searchOrder.length()>0) { - if (searchOrder.equals("datedesc")) - queryBuilder.appendAscendingOrder("webdb_create"); - else if (searchOrder.equals("dateasc")) - queryBuilder.appendDescendingOrder("webdb_create"); - else if (searchOrder.equals("articletitle")) - queryBuilder.appendAscendingOrder("(select content.title from content where content.id = comment.to_media)"); - else if (searchOrder.equals("creator")) - queryBuilder.appendDescendingOrder("creator"); - } - - returnCommentList(aRequest, aResponse, queryBuilder.getWhereClause(), queryBuilder.getOrderByClause(), 0); - } - - public void articlecomments(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { - String articleIdString = aRequest.getParameter("articleid"); - int articleId; - - try { - articleId = Integer.parseInt(articleIdString); - - returnCommentList( aRequest, aResponse, "to_media="+articleId, "webdb_create desc", 0); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - public void returnCommentList(HttpServletRequest aRequest, HttpServletResponse aResponse, - String aWhereClause, String anOrderByClause, int anOffset) throws ServletModuleExc { - - 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 commentList = - new CachingRewindableIterator( - new EntityIteratorAdapter( aWhereClause, anOrderByClause, nrEntitiesPerListPage, - MirGlobal.localizer().dataModel().adapterModel(), "comment", nrEntitiesPerListPage, anOffset) - ); - - responseData.put("nexturl", null); - responseData.put("prevurl", null); - - count=mainModule.getSize(aWhereClause); - - urlBuilder.setValue("module", "Comment"); - urlBuilder.setValue("do", "list"); - urlBuilder.setValue("where", aWhereClause); - 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()); - } - - if (anOffset>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+nrEntitiesPerListPage, count))); - - ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { - try { - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - - String returnUrl = requestParser.getParameter("returnurl"); - - String idParam = aRequest.getParameter("id"); - if (idParam == null) - throw new ServletModuleExc("Wrong call: (id) is missing"); - - Map withValues = getIntersectingValues(aRequest, DatabaseComment.getInstance()); - - String content_id = aRequest.getParameter("id"); - - if (!withValues.containsKey("is_published")) - withValues.put("is_published","0"); - if (!withValues.containsKey("is_html")) - withValues.put("is_html","0"); - - String webdbCreate = (String) withValues.get("webdb_create"); - if (webdbCreate==null || webdbCreate.trim().length()==0) - withValues.remove("webdb_create"); - - String id = mainModule.set(withValues); - - if (returnUrl!=null){ - redirect(aResponse, returnUrl); - } - else - showComment(idParam, aRequest, aResponse); - } - 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 mir.entity.adapter.EntityAdapterModel; +import mir.entity.adapter.EntityIteratorAdapter; +import mir.log.LoggerWrapper; +import mir.servlet.ServletModule; +import mir.servlet.ServletModuleExc; +import mir.servlet.ServletModuleFailure; +import mir.servlet.ServletModuleUserExc; +import mir.util.*; +import mircoders.entity.EntityComment; +import mircoders.global.MirGlobal; +import mircoders.module.ModuleComment; +import mircoders.storage.DatabaseComment; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.*; + +/* + * ServletModuleComment - controls navigation for Comments + * + * + * @author the mir-coders + */ + +public class ServletModuleComment extends ServletModule +{ + private static ServletModuleComment instance = new ServletModuleComment(); + public static ServletModule getInstance() { return instance; } + + private ServletModuleComment() { + logger = new LoggerWrapper("ServletModule.Comment"); + try { + mainModule = new ModuleComment(); + } + catch (Exception e) { + logger.error("servletmodule comment could not be initialized:" + e.getMessage()); + } + } + + public void delete(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { + try { + MirGlobal.accessControl().general().assertMayDeleteComments(ServletHelper.getUser(aRequest)); + + super.delete(aRequest, aResponse); + } + catch (Throwable t) { + throw new ServletModuleFailure(t); + } + } + + public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc + { + String idParam = aRequest.getParameter("id"); + + if (idParam == null) + throw new ServletModuleExc("Invalid call: id not supplied "); + + editObject(aRequest, aResponse, idParam); + } + + public void editObject(HttpServletRequest aRequest, HttpServletResponse aResponse, String anId) 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 comment; + URLBuilder urlBuilder = new URLBuilder(); + + urlBuilder.setValue("module", "Comment"); + urlBuilder.setValue("do", "edit"); + urlBuilder.setValue("id", anId); + urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl")); + + if (anId != null) { + responseData.put("new", Boolean.FALSE); + comment = model.makeEntityAdapter("comment", mainModule.getById(anId)); + } + else { + List fields = DatabaseComment.getInstance().getFields(); + responseData.put("new", Boolean.TRUE); + comment = new HashMap(); + Iterator i = fields.iterator(); + while (i.hasNext()) { + comment.put(i.next(), null); + } + } + responseData.put("comment", comment); + + 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 attach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc + { + String mediaIdParam = aRequest.getParameter("mid"); + String commentId = aRequest.getParameter("commentid"); + + if (commentId == null || mediaIdParam==null) throw new ServletModuleExc("smod comment :: attach :: commentid/mid missing"); + + try { + EntityComment comment = (EntityComment) mainModule.getById(commentId); + comment.attach(mediaIdParam); + } + catch(Throwable e) { + throw new ServletModuleFailure(e); + } + + logAdminUsage(aRequest, commentId, "media " + mediaIdParam + " attached"); + + editObject(aRequest, aResponse, commentId); + } + + public void dettach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc + { + String commentId = aRequest.getParameter("commentid"); + String midParam = aRequest.getParameter("mid"); + if (commentId == null) + throw new ServletModuleExc("smod comment :: dettach :: commentid missing"); + if (midParam == null) + throw new ServletModuleExc("smod comment :: dettach :: mid missing"); + + try { + EntityComment comment = (EntityComment)mainModule.getById(commentId); + comment.dettach(commentId, midParam); + } + catch(Throwable e) { + throw new ServletModuleFailure(e); + } + + logAdminUsage(aRequest, commentId, "media " + midParam + " deattached"); + + editObject(aRequest, aResponse, commentId); + } + + + public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc + { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + + String where = requestParser.getParameter("where"); + String order = requestParser.getParameterWithDefault("order", "webdb_create desc"); + int offset = requestParser.getIntegerWithDefault("offset", 0); + + returnList(aRequest, aResponse, where, order, offset); + } + + public void search(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc + { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + SQLQueryBuilder queryBuilder = new SQLQueryBuilder(); + + String searchField = requestParser.getParameter("searchfield"); + String searchText = requestParser.getParameter("searchtext"); + String searchIsPublished = requestParser.getParameter("searchispublished"); + String searchStatus = requestParser.getParameter("searchstatus"); + String searchOrder = requestParser.getParameter("searchorder"); + + if (searchIsPublished.equals("0")) { + queryBuilder.appendAndCondition("is_published='f'"); + } + else if (searchIsPublished.equals("1")) { + queryBuilder.appendAndCondition("is_published='t'"); + } + + if (searchText.length()>0) { + queryBuilder.appendAndCondition( + "lower("+ searchField + ") like " + + "'%" + JDBCStringRoutines.escapeStringLiteral(searchText.toLowerCase()) + "%'"); + } + + if (searchStatus.length()>0) { + queryBuilder.appendAndCondition("to_comment_status="+Integer.parseInt(searchStatus)); + } + + if (searchOrder.length()>0) { + if (searchOrder.equals("datedesc")) + queryBuilder.appendDescendingOrder("webdb_create"); + else if (searchOrder.equals("dateasc")) + queryBuilder.appendAscendingOrder("webdb_create"); + else if (searchOrder.equals("articletitle")) + queryBuilder.appendAscendingOrder("(select content.title from content where content.id = comment.to_media)"); + else if (searchOrder.equals("creator")) + queryBuilder.appendDescendingOrder("creator"); + } + + returnList(aRequest, aResponse, queryBuilder.getWhereClause(), queryBuilder.getOrderByClause(), 0); + } + + public void articlecomments(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc + { + String articleIdString = aRequest.getParameter("articleid"); + int articleId; + + try { + articleId = Integer.parseInt(articleIdString); + + returnList( aRequest, aResponse, "to_media="+articleId, "webdb_create desc", 0); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + 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 { + Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}); + + Object commentList = + new CachingRewindableIterator( + new EntityIteratorAdapter( aWhereClause, anOrderByClause, nrEntitiesPerListPage, + MirGlobal.localizer().dataModel().adapterModel(), "comment", nrEntitiesPerListPage, anOffset) + ); + + responseData.put("nexturl", null); + responseData.put("prevurl", null); + + count=mainModule.getSize(aWhereClause); + + urlBuilder.setValue("module", "Comment"); + 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()); + } + + if (anOffset>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+nrEntitiesPerListPage, count))); + + ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc + { + try { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + + String returnUrl = requestParser.getParameter("returnurl"); + + String idParam = aRequest.getParameter("id"); + if (idParam == null) + throw new ServletModuleExc("Wrong call: (id) is missing"); + + Map withValues = getIntersectingValues(aRequest, DatabaseComment.getInstance()); + + if (!withValues.containsKey("is_published")) + withValues.put("is_published","0"); + if (!withValues.containsKey("is_html")) + withValues.put("is_html","0"); + + String webdbCreate = (String) withValues.get("webdb_create"); + if (webdbCreate==null || webdbCreate.trim().length()==0) + withValues.remove("webdb_create"); + + String id = mainModule.set(withValues); + + logAdminUsage(aRequest, id, "object modified"); + + if (returnUrl!=null){ + ServletHelper.redirect(aResponse, returnUrl); + } + else + editObject(aRequest, aResponse, idParam); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } } \ No newline at end of file diff --git a/source/mircoders/servlet/ServletModuleCommentStatus.java b/source/mircoders/servlet/ServletModuleCommentStatus.java index 7696feea..71767a0b 100755 --- a/source/mircoders/servlet/ServletModuleCommentStatus.java +++ b/source/mircoders/servlet/ServletModuleCommentStatus.java @@ -29,12 +29,9 @@ */ package mircoders.servlet; -import mir.config.MirPropertiesConfiguration; import mir.log.LoggerWrapper; import mir.servlet.ServletModule; import mircoders.module.ModuleCommentStatus; -import mircoders.storage.DatabaseCommentStatus; -import mircoders.global.*; public class ServletModuleCommentStatus extends ServletModule @@ -46,9 +43,8 @@ public class ServletModuleCommentStatus extends ServletModule logger = new LoggerWrapper("ServletModule.CommentStatus"); try { - model = MirGlobal.localizer().dataModel().adapterModel(); definition = "commentStatus"; - mainModule = new ModuleCommentStatus(DatabaseCommentStatus.getInstance()); + mainModule = new ModuleCommentStatus(); } 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 c9d65863..a3a1c324 100755 --- a/source/mircoders/servlet/ServletModuleContent.java +++ b/source/mircoders/servlet/ServletModuleContent.java @@ -1,490 +1,655 @@ -/* - * 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.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import mir.entity.adapter.EntityAdapterModel; -import mir.entity.adapter.EntityIteratorAdapter; -import mir.log.LoggerWrapper; -import mir.misc.StringUtil; -import mir.servlet.ServletModule; -import mir.servlet.ServletModuleExc; -import mir.servlet.ServletModuleFailure; -import mir.util.CachingRewindableIterator; -import mir.util.HTTPRequestParser; -import mir.util.JDBCStringRoutines; -import mir.util.SQLQueryBuilder; -import mir.util.URLBuilder; -import mircoders.entity.EntityContent; -import mircoders.global.MirGlobal; -import mircoders.module.ModuleContent; -import mircoders.storage.DatabaseContent; -import mircoders.storage.DatabaseContentToTopics; - -/* - * ServletModuleContent - - * deliver html for the article admin form. - * - * @version $Id: ServletModuleContent.java,v 1.53 2003/09/03 18:29:05 zapata Exp $ - * @author rk, mir-coders - * - */ - -public class ServletModuleContent extends ServletModule -{ - private static ServletModuleContent instance = new ServletModuleContent(); - public static ServletModule getInstance() { return instance; } - - private ServletModuleContent() { - super(); - - logger = new LoggerWrapper("ServletModule.Content"); - - try { - mainModule = new ModuleContent(DatabaseContent.getInstance()); - } - catch (Throwable e) { - logger.fatal("ServletModuleContent could not be initialized: " + e.toString()); - } - } - - public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - - String where = requestParser.getParameter("where"); - String order = requestParser.getParameterWithDefault("order", "webdb_create desc"); - int offset = requestParser.getIntegerWithDefault("offset", 0); - String selectArticleUrl = requestParser.getParameter("selectarticleurl"); - - returnArticleList(aRequest, aResponse, where, order, offset, selectArticleUrl); - } - - public void search(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleFailure { - try { - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - SQLQueryBuilder queryBuilder = new SQLQueryBuilder(); - String searchField = requestParser.getParameterWithDefault("searchfield", ""); - String searchValue = requestParser.getParameterWithDefault("searchvalue", "").trim(); - String searchOrder = requestParser.getParameterWithDefault("searchorder", ""); - String searchispublished = requestParser.getParameterWithDefault("searchispublished", ""); - String searchArticleType = requestParser.getParameterWithDefault("searcharticletype", ""); - String selectArticleUrl = requestParser.getParameter("selectarticleurl"); - - if (searchValue.length()>0) { - if (searchField.equals("id")) - queryBuilder.appendAndCondition( - "id='"+JDBCStringRoutines.escapeStringLiteral(searchValue)+"'"); - else if (searchField.equals("contents")) - queryBuilder.appendAndCondition( - "(lower(content_data) like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%')"+ - " or (lower(description) like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%')"); - else - queryBuilder.appendAndCondition( - "lower("+ searchField + ") like " + - "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%'"); - } - - if (searchispublished.length()>0) { - if (searchispublished.equals("0")) - queryBuilder.appendAndCondition("is_published='f'"); - else - queryBuilder.appendAndCondition("is_published='t'"); - } - - if (searchArticleType.length()>0) { - queryBuilder.appendAndCondition("to_article_type="+Integer.parseInt(searchArticleType)); - } - - if (searchOrder.length()>0) { - if (searchOrder.equals("datedesc")) - queryBuilder.appendDescendingOrder("webdb_create"); - else if (searchOrder.equals("dateasc")) - queryBuilder.appendAscendingOrder("webdb_create"); - else if (searchOrder.equals("title")) - queryBuilder.appendAscendingOrder("title"); - else if (searchOrder.equals("creator")) - queryBuilder.appendAscendingOrder("creator"); - } - - returnArticleList(aRequest, aResponse, queryBuilder.getWhereClause(), queryBuilder.getOrderByClause(), 0, selectArticleUrl); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - public void add(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { - _showObject(null, aRequest, aResponse); - } - - - public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { -//theLog.printDebugInfo(":: content :: trying to insert"); - try { - Map withValues = getIntersectingValues(aRequest, DatabaseContent.getInstance()); - - String now = StringUtil.date2webdbDate(new GregorianCalendar()); - withValues.put("date", now); - withValues.put("publish_path", StringUtil.webdbDate2path(now)); - withValues.put("to_publisher", ServletHelper.getUser(aRequest).getId()); - withValues.put("is_produced", "0"); - if (!withValues.containsKey("is_published")) - withValues.put("is_published","0"); - if (!withValues.containsKey("is_html")) - withValues.put("is_html","0"); - - String webdbCreate = (String) withValues.get("webdb_create"); - if (webdbCreate==null || webdbCreate.trim().length()==0) - withValues.remove("webdb_create"); - - String id = mainModule.add(withValues); - List topics; - - DatabaseContentToTopics.getInstance().setTopics(id, aRequest.getParameterValues("to_topic")); - - _showObject(id, aRequest, aResponse); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { - String idParam = aRequest.getParameter("id"); - if (idParam == null) - throw new ServletModuleExc("Invalid call: id not supplied "); - _showObject(idParam, aRequest, aResponse); - } - -// methods for attaching media file - public void attach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { - String mediaIdParam = aRequest.getParameter("mid"); - String articleId = aRequest.getParameter("articleid"); - - if (articleId == null || mediaIdParam==null) - throw new ServletModuleExc("smod content :: attach :: articleid/mid missing"); - - try { - EntityContent entContent = (EntityContent) mainModule.getById(articleId); - entContent.attach(mediaIdParam); - } - catch(Throwable e) { - throw new ServletModuleFailure(e); - } - - _showObject(articleId, aRequest, aResponse); - } - - public void dettach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { - String articleId = aRequest.getParameter("articleid"); - String midParam = aRequest.getParameter("mid"); - if (articleId == null) - throw new ServletModuleExc("smod content :: dettach :: articleid missing"); - if (midParam == null) - throw new ServletModuleExc("smod content :: dettach :: mid missing"); - - try { - EntityContent entContent = (EntityContent)mainModule.getById(articleId); - entContent.dettach(articleId, midParam); - } - catch(Throwable e) { - throw new ServletModuleFailure(e); - } - - _showObject(articleId, aRequest, aResponse); - } - - public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { - try { - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - - String returnUrl = requestParser.getParameter("returnurl"); - - String idParam = aRequest.getParameter("id"); - if (idParam == null) - throw new ServletModuleExc("Wrong call: (id) is missing"); - - Map withValues = getIntersectingValues(aRequest, DatabaseContent.getInstance()); - - String content_id = aRequest.getParameter("id"); - - withValues.put("is_produced", "0"); - if (!withValues.containsKey("is_published")) - withValues.put("is_published","0"); - if (!withValues.containsKey("is_html")) - withValues.put("is_html","0"); - - String webdbCreate = (String) withValues.get("webdb_create"); - if (webdbCreate==null || webdbCreate.trim().length()==0) - withValues.remove("webdb_create"); - - String id = mainModule.set(withValues); - DatabaseContentToTopics.getInstance().setTopics(aRequest.getParameter("id"), aRequest.getParameterValues("to_topic")); - - if (returnUrl!=null && !returnUrl.equals("")){ - redirect(aResponse, returnUrl); - } - else - _showObject(idParam, aRequest, aResponse); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - - /** - * HelperMethod shows the basic article editing form. - * - * if the "id" parameter is null, it means show an empty form to add a new - * article. - * - * @param id - * @param aRequest - * @param aResponse - * @throws ServletModuleExc - */ - public void _showObject(String id, 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 article; - URLBuilder urlBuilder = new URLBuilder(); - - urlBuilder.setValue("module", "Content"); - urlBuilder.setValue("do", "edit"); - urlBuilder.setValue("id", id); - urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl")); - - if (id!=null) { - responseData.put("new", Boolean.FALSE); - article = model.makeEntityAdapter("content", mainModule.getById(id)); - } - else { - List fields = DatabaseContent.getInstance().getFields(); - responseData.put("new", Boolean.TRUE); - article = new HashMap(); - Iterator i = fields.iterator(); - while (i.hasNext()) { - article.put(i.next(), null); - } - - article.put("to_topics", null); - - MirGlobal.localizer().adminInterface().initializeArticle(article); - } - responseData.put("article", article); - - responseData.put("topics", - new EntityIteratorAdapter("", configuration.getString("Mir.Localizer.Admin.TopicListOrder"), - 20, MirGlobal.localizer().dataModel().adapterModel(), "topic")); - - 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 returnArticleList( - HttpServletRequest aRequest, - HttpServletResponse aResponse, - String aWhereClause, - String anOrderByClause, - int anOffset, - String aSelectArticleUrl) throws ServletModuleExc { - - 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 articleList = - new CachingRewindableIterator( - new EntityIteratorAdapter( aWhereClause, anOrderByClause, nrEntitiesPerListPage, - MirGlobal.localizer().dataModel().adapterModel(), "content", nrEntitiesPerListPage, anOffset) - ); - - responseData.put("nexturl", null); - responseData.put("prevurl", null); - - count=mainModule.getSize(aWhereClause); - - urlBuilder.setValue("module", "Content"); - urlBuilder.setValue("do", "list"); - urlBuilder.setValue("where", aWhereClause); - urlBuilder.setValue("order", anOrderByClause); - - - urlBuilder.setValue("searchfield", requestParser.getParameter("searchfield")); - urlBuilder.setValue("searchvalue", requestParser.getParameter("searchvalue")); - urlBuilder.setValue("searchispublished", requestParser.getParameter("searchispublished")); - urlBuilder.setValue("searchorder", requestParser.getParameter("searchorder")); - urlBuilder.setValue("searcharticletype", requestParser.getParameter("searcharticletype")); - urlBuilder.setValue("selectarticleurl", aSelectArticleUrl); - - responseData.put("searchfield", requestParser.getParameter("searchfield")); - responseData.put("searchvalue", requestParser.getParameter("searchvalue")); - responseData.put("searchispublished", requestParser.getParameter("searchispublished")); - responseData.put("searchorder", requestParser.getParameter("searchorder")); - responseData.put("searcharticletype", requestParser.getParameter("searcharticletype")); - responseData.put("selectarticleurl", aSelectArticleUrl); - - 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("articles", articleList); - - 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)); - responseData.put("order", anOrderByClause); - responseData.put("where" , aWhereClause); - - ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - public void selectparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { - try { - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - URLBuilder urlBuilder = new URLBuilder(); - - urlBuilder.setValue("module", "Content"); - urlBuilder.setValue("do", "setparent"); - urlBuilder.setValue("childid", requestParser.getParameter("id")); - urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl")); - - returnArticleList(aRequest, aResponse, "", "", 0, urlBuilder.getQuery()); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - public void listchildren(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { - try { - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - String articleId = requestParser.getParameter("article_id"); - - if (articleId == null) - throw new ServletModuleExc("ServletModuleContent.listchildren: article_id not set!"); - - returnArticleList(aRequest, aResponse, "to_content = " + articleId, "", 0, null); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - public void setparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - String articleId = aRequest.getParameter("childid"); - String parentId = aRequest.getParameter("id"); - String returnUrl = aRequest.getParameter("returnurl"); - - try { - EntityContent article = (EntityContent) mainModule.getById(articleId); - article.setValueForProperty("to_content", parentId); - article.setProduced(false); - article.update(); - } - catch(Throwable e) { - logger.error("ServletModuleContent.setparent: " + e.getMessage()); - throw new ServletModuleFailure(e); - } - - redirect(aResponse, returnUrl); - } - - public void clearparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - String articleId = requestParser.getParameter("id"); - String returnUrl = requestParser.getParameter("returnurl"); - - try { - EntityContent article = (EntityContent) mainModule.getById(articleId); - article.setValueForProperty("to_content", ""); - article.setProduced(false); - article.update(); - } - catch(Throwable e) { - e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); - logger.error("ServletModuleContent.clearparent: " + e.getMessage()); - - throw new ServletModuleFailure("ServletModuleContent.clearparent: " + e.getMessage(), e); - } - - redirect(aResponse, returnUrl); - } -} +/* + * 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.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Vector; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import mir.entity.adapter.EntityAdapterModel; +import mir.entity.adapter.EntityIteratorAdapter; +import mir.entity.adapter.EntityAdapter; +import mir.log.LoggerWrapper; +import mir.misc.StringUtil; +import mir.servlet.ServletModule; +import mir.servlet.ServletModuleExc; +import mir.servlet.ServletModuleFailure; +import mir.util.CachingRewindableIterator; +import mir.util.HTTPRequestParser; +import mir.util.JDBCStringRoutines; +import mir.util.SQLQueryBuilder; +import mir.util.StringRoutines; +import mir.util.URLBuilder; +import mir.generator.Generator; +import mircoders.entity.*; +import mircoders.global.MirGlobal; +import mircoders.module.ModuleContent; +import mircoders.storage.DatabaseContent; +import mircoders.storage.DatabaseContentToTopics; + +/** + * Article admin interface code + */ + +public class ServletModuleContent extends ServletModule +{ + private static ServletModuleContent instance = new ServletModuleContent(); + public static ServletModule getInstance() { return instance; } + private static ModuleContent contentModule; + + private ServletModuleContent() { + super(); + + logger = new LoggerWrapper("ServletModule.Content"); + + try { + contentModule = new ModuleContent(); + mainModule = contentModule; + } + catch (Throwable e) { + logger.fatal("ServletModuleContent could not be initialized: " + e.toString()); + } + } + + public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc + { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + + String where = requestParser.getParameter("where"); + String order = requestParser.getParameterWithDefault("order", "webdb_create desc"); + int offset = requestParser.getIntegerWithDefault("offset", 0); + String selectArticleUrl = requestParser.getParameter("selectarticleurl"); + + returnList(aRequest, aResponse, where, order, offset, selectArticleUrl); + } + + public void search(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleFailure { + try { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + SQLQueryBuilder queryBuilder = new SQLQueryBuilder(); + String searchField = requestParser.getParameterWithDefault("searchfield", ""); + String searchValue = requestParser.getParameterWithDefault("searchvalue", "").trim(); + String searchOrder = requestParser.getParameterWithDefault("searchorder", ""); + String searchispublished = requestParser.getParameterWithDefault("searchispublished", ""); + String searchArticleType = requestParser.getParameterWithDefault("searcharticletype", ""); + String selectArticleUrl = requestParser.getParameter("selectarticleurl"); + + if (searchValue.length()>0) { + if (searchField.equals("id")) + queryBuilder.appendAndCondition( + "id='"+JDBCStringRoutines.escapeStringLiteral(searchValue)+"'"); + else if (searchField.equals("contents")) + queryBuilder.appendAndCondition( + "(lower(content_data) like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%')"+ + " or (lower(description) like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%')"); + else + queryBuilder.appendAndCondition( + "lower("+ searchField + ") like " + + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%'"); + } + + if (searchispublished.length()>0) { + if (searchispublished.equals("0")) + queryBuilder.appendAndCondition("is_published='f'"); + else + queryBuilder.appendAndCondition("is_published='t'"); + } + + if (searchArticleType.length()>0) { + queryBuilder.appendAndCondition("to_article_type="+Integer.parseInt(searchArticleType)); + } + + if (searchOrder.length()>0) { + if (searchOrder.equals("datedesc")) + queryBuilder.appendDescendingOrder("webdb_create"); + else if (searchOrder.equals("dateasc")) + queryBuilder.appendAscendingOrder("webdb_create"); + else if (searchOrder.equals("title")) + queryBuilder.appendAscendingOrder("title"); + else if (searchOrder.equals("creator")) + queryBuilder.appendAscendingOrder("creator"); + } + + returnList(aRequest, aResponse, queryBuilder.getWhereClause(), queryBuilder.getOrderByClause(), 0, selectArticleUrl); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + public void add(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { + editObject(aRequest, aResponse, null); + } + + public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { + try { + Map withValues = getIntersectingValues(aRequest, DatabaseContent.getInstance()); + + String now = StringUtil.date2webdbDate(new GregorianCalendar()); + withValues.put("date", now); + withValues.put("publish_path", StringUtil.webdbDate2path(now)); + withValues.put("to_publisher", ServletHelper.getUser(aRequest).getId()); + withValues.put("is_produced", "0"); + if (!withValues.containsKey("is_published")) + withValues.put("is_published","0"); + if (!withValues.containsKey("is_html")) + withValues.put("is_html","0"); + + String webdbCreate = (String) withValues.get("webdb_create"); + if (webdbCreate==null || webdbCreate.trim().length()==0) + withValues.remove("webdb_create"); + + String id = mainModule.add(withValues); + logAdminUsage(aRequest, id, "object added"); + + DatabaseContentToTopics.getInstance().setTopics(id, aRequest.getParameterValues("to_topic")); + + editObject(aRequest, aResponse, id); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { + String idParam = aRequest.getParameter("id"); + if (idParam == null) + throw new ServletModuleExc("Invalid call: id not supplied "); + editObject(aRequest, aResponse, idParam); + } + + /** + * Attaches media to an article + * + */ + public void attach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { + String mediaIdParam = aRequest.getParameter("mid"); + String articleId = aRequest.getParameter("articleid"); + + if (articleId == null || mediaIdParam==null) + throw new ServletModuleExc("smod content :: attach :: articleid/mid missing"); + + if (!MirGlobal.accessControl().article().mayEditArticle(ServletHelper.getUser(aRequest), articleId)) + throw new ServletModuleExc("Article has been locked"); + + try { + EntityContent entContent = (EntityContent) mainModule.getById(articleId); + entContent.attach(mediaIdParam); + } + catch(Throwable e) { + throw new ServletModuleFailure(e); + } + + logAdminUsage(aRequest, articleId, "media " + mediaIdParam + " attached"); + + editObject(aRequest, aResponse, articleId); + } + + /** + * Deattaches media from an article + */ + public void dettach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc + { + String articleId = aRequest.getParameter("articleid"); + String midParam = aRequest.getParameter("mid"); + if (articleId == null) + throw new ServletModuleExc("smod content :: dettach :: articleid missing"); + if (midParam == null) + throw new ServletModuleExc("smod content :: dettach :: mid missing"); + + if (!MirGlobal.accessControl().article().mayEditArticle(ServletHelper.getUser(aRequest), articleId)) + throw new ServletModuleExc("Article has been locked"); + + try { + EntityContent entContent = (EntityContent)mainModule.getById(articleId); + entContent.dettach(articleId, midParam); + } + catch(Throwable e) { + throw new ServletModuleFailure(e); + } + + logAdminUsage(aRequest, articleId, "media " + midParam + " deattached"); + + editObject(aRequest, aResponse, articleId); + } + + /** + * Locks an article + */ + public void lock(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc + { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + + String idParam = requestParser.getParameter("id"); + if (idParam == null) + throw new ServletModuleExc("Wrong call: (id) is missing"); + + EntityUsers user = ServletHelper.getUser(aRequest); + + if (!MirGlobal.accessControl().article().mayLockArticle(user, idParam)) + throw new ServletModuleExc("Unable to lock"); + + contentModule.lockArticle(idParam, user.getId(), false); + + editObject(aRequest, aResponse, idParam); + } + + /** + * Unlocks an article + */ + public void unlock(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc + { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + + String idParam = requestParser.getParameter("id"); + if (idParam == null) + throw new ServletModuleExc("Wrong call: (id) is missing"); + + EntityUsers user = ServletHelper.getUser(aRequest); + + if (!MirGlobal.accessControl().article().mayUnlockArticle(user, idParam)) + throw new ServletModuleExc("Unable to unlock"); + + contentModule.unlockArticle(idParam, user.getId(), false); + + editObject(aRequest, aResponse, idParam); + } + + /** + * Forcelocks an article + */ + public void forcelock(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc + { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + + String idParam = requestParser.getParameter("id"); + if (idParam == null) + throw new ServletModuleExc("Wrong call: (id) is missing"); + + EntityUsers user = ServletHelper.getUser(aRequest); + + if (!MirGlobal.accessControl().article().mayForceLockArticle(user, idParam)) + throw new ServletModuleExc("Unable to force lock"); + + contentModule.lockArticle(idParam, user.getId(), true); + + editObject(aRequest, aResponse, idParam); + } + + /** + * Stores an article + */ + public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc + { + try { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + + String idParam = requestParser.getParameter("id"); + if (idParam == null) + throw new ServletModuleExc("Wrong call: (id) is missing"); + + if (!MirGlobal.accessControl().article().mayEditArticle(ServletHelper.getUser(aRequest), idParam)) + throw new ServletModuleExc("Article has been locked"); + + Map withValues = getIntersectingValues(aRequest, DatabaseContent.getInstance()); + + withValues.put("is_produced", "0"); + if (!withValues.containsKey("is_published")) + withValues.put("is_published","0"); + if (!withValues.containsKey("is_html")) + withValues.put("is_html","0"); + + String webdbCreate = (String) withValues.get("webdb_create"); + if (webdbCreate==null || webdbCreate.trim().length()==0) + withValues.remove("webdb_create"); + + String id = mainModule.set(withValues); + + logAdminUsage(aRequest, id, "object modified"); + + DatabaseContentToTopics.getInstance().setTopics(aRequest.getParameter("id"), aRequest.getParameterValues("to_topic")); + + if (MirGlobal.accessControl().article().mayUnlockArticle(ServletHelper.getUser(aRequest), idParam) && + (requestParser.getParameterWithDefault("unlock", "0").equals("1"))) { + contentModule.unlockArticle(id, ServletHelper.getUser(aRequest).getId(), false); + } + + editObject(aRequest, aResponse, idParam); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + + /** + * Returns the basic article editing form. + * + * @param id identifier of the article. null, means show an + * empty form to add a new article. + */ + public void editObject(HttpServletRequest aRequest, HttpServletResponse aResponse, String id) + 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 article; + URLBuilder urlBuilder = new URLBuilder(); + + urlBuilder.setValue("module", "Content"); + urlBuilder.setValue("do", "edit"); + urlBuilder.setValue("id", id); + urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl")); + + if (id!=null) { + responseData.put("new", Boolean.FALSE); + article = model.makeEntityAdapter("content", mainModule.getById(id)); + + EntityUsers user = ServletHelper.getUser(aRequest); + + responseData.put("mayEdit", new Boolean(MirGlobal.accessControl().article().mayEditArticle(user, id))); + responseData.put("mayLock", new Boolean(MirGlobal.accessControl().article().mayLockArticle(user, id))); + responseData.put("mayForceLock", new Boolean(MirGlobal.accessControl().article().mayForceLockArticle(user, id))); + responseData.put("mayUnlock", new Boolean(MirGlobal.accessControl().article().mayUnlockArticle(user, id))); + } + else { + List fields = DatabaseContent.getInstance().getFields(); + responseData.put("new", Boolean.TRUE); + article = new HashMap(); + Iterator i = fields.iterator(); + while (i.hasNext()) { + article.put(i.next(), null); + } + + article.put("to_topics", null); + + MirGlobal.localizer().adminInterface().initializeArticle(article); + + responseData.put("mayEdit", Boolean.TRUE); + responseData.put("mayLock", Boolean.FALSE); + responseData.put("mayForceLock", Boolean.FALSE); + responseData.put("mayUnlock", Boolean.FALSE); + } + responseData.put("article", article); + + List topicsList = new Vector(); + + String[] topicCategories = configuration.getStringArray("Mir.Localizer.Admin.TopicLists"); + + if (topicCategories.length==0 ) { + Map categoryMap = new HashMap(); + categoryMap.put("key", "topic"); + categoryMap.put("listtype", "0"); + categoryMap.put("listparameter", "3"); + categoryMap.put("items", + new EntityIteratorAdapter("", "title", + 20, MirGlobal.localizer().dataModel().adapterModel(), "topic")); + topicsList.add(categoryMap); + } + else + { + + for (int i = 0; i < topicCategories.length; i++) { + try { + Map categoryMap = new HashMap(); + List parts = StringRoutines.splitString(topicCategories[i], ":"); + String key = null; + String listtype = "0"; + String listparameter = "5"; + String where = ""; + String order = ""; + + if (parts.size() > 0) + key = (String) parts.get(0); + if (parts.size() > 1) + listtype = (String) parts.get(1); + if (parts.size() > 2) + listparameter = (String) parts.get(2); + if (parts.size() > 3) + where = (String) parts.get(3); + if (parts.size() > 4) + order = (String) parts.get(4); + + if (key != null) { + categoryMap.put("key", key); + categoryMap.put("listtype", listtype); + categoryMap.put("listparameter", listparameter); + categoryMap.put("items", + new EntityIteratorAdapter(where, order, + 20, MirGlobal.localizer().dataModel().adapterModel(), "topic")); + topicsList.add(categoryMap); + } + } + catch (Throwable t) { + logger.error("error while preparing topics: " + t.toString()); + } + } + } + + responseData.put("topics", topicsList); + + 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 returnList(HttpServletRequest aRequest, HttpServletResponse aResponse, + String aWhereClause, String anOrderByClause, int anOffset) throws ServletModuleExc { + this.returnList(aRequest, aResponse, aWhereClause, anOrderByClause, anOffset, null); + } + + public void returnList( + HttpServletRequest aRequest, + HttpServletResponse aResponse, + String aWhereClause, + String anOrderByClause, + int anOffset, + String aSelectArticleUrl) throws ServletModuleExc { + + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + URLBuilder urlBuilder = new URLBuilder(); + int count; + + try { + Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}); + Object articleList = + new CachingRewindableIterator( + new EntityIteratorAdapter( aWhereClause, anOrderByClause, nrEntitiesPerListPage, + MirGlobal.localizer().dataModel().adapterModel(), "content", nrEntitiesPerListPage, anOffset) + ); + + responseData.put("nexturl", null); + responseData.put("prevurl", null); + + count=mainModule.getSize(aWhereClause); + + urlBuilder.setValue("module", "Content"); + urlBuilder.setValue("do", "list"); + urlBuilder.setValue("where", aWhereClause); + urlBuilder.setValue("order", anOrderByClause); + + + urlBuilder.setValue("searchfield", requestParser.getParameter("searchfield")); + urlBuilder.setValue("searchvalue", requestParser.getParameter("searchvalue")); + urlBuilder.setValue("searchispublished", requestParser.getParameter("searchispublished")); + urlBuilder.setValue("searchorder", requestParser.getParameter("searchorder")); + urlBuilder.setValue("searcharticletype", requestParser.getParameter("searcharticletype")); + urlBuilder.setValue("selectarticleurl", aSelectArticleUrl); + + responseData.put("searchfield", requestParser.getParameter("searchfield")); + responseData.put("searchvalue", requestParser.getParameter("searchvalue")); + responseData.put("searchispublished", requestParser.getParameter("searchispublished")); + responseData.put("searchorder", requestParser.getParameter("searchorder")); + responseData.put("searcharticletype", requestParser.getParameter("searcharticletype")); + responseData.put("selectarticleurl", aSelectArticleUrl); + + 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("articles", articleList); + + 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)); + responseData.put("order", anOrderByClause); + responseData.put("where" , aWhereClause); + + ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + public void selectparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc + { + try { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + URLBuilder urlBuilder = new URLBuilder(); + + urlBuilder.setValue("module", "Content"); + urlBuilder.setValue("do", "setparent"); + urlBuilder.setValue("childid", requestParser.getParameter("id")); + urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl")); + + returnList(aRequest, aResponse, "", "", 0, urlBuilder.getQuery()); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + public void listchildren(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { + try { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + String articleId = requestParser.getParameter("article_id"); + + if (articleId == null) + throw new ServletModuleExc("ServletModuleContent.listchildren: article_id not set!"); + + returnList(aRequest, aResponse, "to_content = " + articleId, "", 0, null); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + public void setparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc + { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + String articleId = requestParser.getParameter("childid"); + String parentId = requestParser.getParameter("id"); + String returnUrl = requestParser.getParameter("returnurl"); + + if (!MirGlobal.accessControl().article().mayEditArticle(ServletHelper.getUser(aRequest), articleId)) + throw new ServletModuleExc("Article has been locked"); + + try { + EntityContent article = (EntityContent) mainModule.getById(articleId); + article.setFieldValue("to_content", parentId); + article.setProduced(false); + article.update(); + logAdminUsage(aRequest, articleId, "parent set to " + parentId); + } + catch(Throwable e) { + logger.error("ServletModuleContent.setparent: " + e.getMessage()); + throw new ServletModuleFailure(e); + } + + ServletHelper.redirect(aResponse, returnUrl); + } + + public void clearparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc + { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + String articleId = requestParser.getParameter("id"); + String returnUrl = requestParser.getParameter("returnurl"); + + try { + EntityContent article = (EntityContent) mainModule.getById(articleId); + article.setFieldValue("to_content", ""); + article.setProduced(false); + article.update(); + logAdminUsage(aRequest, articleId, "parent cleared"); + } + catch(Throwable e) { + e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); + logger.error("ServletModuleContent.clearparent: " + e.getMessage()); + + throw new ServletModuleFailure("ServletModuleContent.clearparent: " + e.getMessage(), e); + } + + ServletHelper.redirect(aResponse, returnUrl); + } + + public void showPreview(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { + try { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + String articleId = requestParser.getParameter("id"); + EntityAdapter article = model.makeEntityAdapter("content", mainModule.getById(articleId)); + String preview = requestParser.getParameterWithDefault("preview", "default"); + + Map generationValues = new HashMap(); + Generator generator = + MirGlobal.localizer().adminInterface().prepareArticlePreview(preview, article, generationValues); + + generator.generate(aResponse.getWriter(), generationValues, logger); + } + catch (Exception e) { + throw new ServletModuleFailure(e); + } + } +} diff --git a/source/mircoders/servlet/ServletModuleFileEdit.java b/source/mircoders/servlet/ServletModuleFileEdit.java index 92ff9c70..65044817 100755 --- a/source/mircoders/servlet/ServletModuleFileEdit.java +++ b/source/mircoders/servlet/ServletModuleFileEdit.java @@ -30,11 +30,12 @@ package mircoders.servlet; +import java.io.BufferedReader; +import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.FilenameFilter; -import java.io.StringReader; import java.io.StringWriter; import java.util.HashMap; import java.util.List; @@ -58,8 +59,8 @@ import mir.util.URLBuilder; * Allows one to do a basic edit of a file in a directory specified * in the config file. * - * @author $Author: zapata $ - * @version $Revision: 1.14 $ $Date: 2003/09/03 18:29:05 $ + * @author $Author: idfx $ + * @version $Revision: 1.15 $ $Date: 2004/11/06 20:09:12 $ * */ @@ -118,7 +119,7 @@ public class ServletModuleFileEdit extends ServletModule String setting = settings[i].trim(); if (setting.length() > 0) { - List parts = StringRoutines.splitString(setting, ":"); + List parts = StringRoutines.splitStringWithEscape(setting, ':', '\\'); if (parts.size() != 4) { logger.error("config error: " + settings[i] + ", 4 parts expected"); } @@ -192,27 +193,37 @@ public class ServletModuleFileEdit extends ServletModule } } + /** + * Called when an edited file is saved by the user + */ public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); String filename = requestParser.getParameter("filename"); String subDirectory = requestParser.getParameter("subdirectory"); - String text = requestParser.getParameter("text"); + String text = + StringRoutines.performRegularExpressionReplacement( + requestParser.getParameter("text"), + "\r\n", + System.getProperty("line.separator")); FileEditDirectory directory = getDirectory(aRequest); try { File f = new File(new File(directory.getRootDirectory(), subDirectory), filename); if (validateDirectory(directory, f)) { - StringReader in = new StringReader(text); FileWriter out = new FileWriter(f); + try { + out.write(text.toCharArray()); + } + finally { + out.close(); + } - int c; - while ( (c = in.read()) != -1) - out.write(c); - in.close(); - out.close(); - + logAdminUsage(aRequest, f.getAbsolutePath(), "object modified"); +/* + MirGlobal.getChangeEngine().getTracker().addChange(f.getCanonicalPath()); +*/ editFile(directory, filename, subDirectory, aRequest, aResponse); } } @@ -276,17 +287,20 @@ public class ServletModuleFileEdit extends ServletModule urlBuilder.setValue("directory", ""); urlBuilder.setValue("subdirectory", aSubDirectory); - FileReader in = new FileReader(f); - StringWriter out = new StringWriter(); + BufferedReader in = new BufferedReader(new FileReader(f)); + StringWriter textout = new StringWriter(); + BufferedWriter out = new BufferedWriter(textout); - int c; - while ( (c = in.read()) != -1) - out.write(c); + // TODO read array + char[] c = new char[4096]; + int read;; + while ( (read=in.read(c)) != -1) + out.write(c, 0, read); in.close(); out.close(); responseData.put("entry", aDirectory.getName()); - responseData.put("text", out.toString()); + responseData.put("text", textout.toString()); responseData.put("filename", aFileName); responseData.put("subdirectory", aSubDirectory); responseData.put("returnurl", urlBuilder.getQuery()); diff --git a/source/mircoders/servlet/ServletModuleHidden.java b/source/mircoders/servlet/ServletModuleHidden.java index 6ae6d20a..03606308 100755 --- a/source/mircoders/servlet/ServletModuleHidden.java +++ b/source/mircoders/servlet/ServletModuleHidden.java @@ -29,24 +29,23 @@ */ package mircoders.servlet; -import java.util.Iterator; -import java.util.Locale; -import java.util.Map; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import mir.entity.adapter.EntityIteratorAdapter; -import mir.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 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 javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.Iterator; +import java.util.Locale; +import java.util.Map; /* * ServletModuleHidden - output of so called "censored" articles @@ -66,7 +65,7 @@ public class ServletModuleHidden extends ServletModule logger = new LoggerWrapper("ServletModule.Hidden"); try { - mainModule = new ModuleContent(DatabaseContent.getInstance()); + mainModule = new ModuleContent(); } catch (StorageObjectFailure e) { logger.error("initialization of servletmoduleHidden failed: " + e.getMessage()); diff --git a/source/mircoders/servlet/ServletModuleImages.java b/source/mircoders/servlet/ServletModuleImages.java index ca90691e..7c60376d 100755 --- a/source/mircoders/servlet/ServletModuleImages.java +++ b/source/mircoders/servlet/ServletModuleImages.java @@ -31,15 +31,11 @@ package mircoders.servlet; import mir.log.LoggerWrapper; 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.27 2003/09/03 18:29:05 zapata Exp $ * @author RK, the mir-coders group */ @@ -56,9 +52,8 @@ public class ServletModuleImages extends ServletModuleUploadedMedia moduleName = "Images"; try { - model = MirGlobal.localizer().dataModel().adapterModel(); definition = "image"; - mainModule = new ModuleImages(DatabaseImages.getInstance()); + mainModule = new ModuleImages(); } 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 d6526cd9..616f3b68 100755 --- a/source/mircoders/servlet/ServletModuleLanguage.java +++ b/source/mircoders/servlet/ServletModuleLanguage.java @@ -31,10 +31,7 @@ package mircoders.servlet; import mir.log.LoggerWrapper; import mir.servlet.ServletModule; -import mir.storage.StorageObjectFailure; import mircoders.module.ModuleLanguage; -import mircoders.storage.DatabaseLanguage; -import mircoders.global.*; /* * ServletModuleLanguage - @@ -54,9 +51,8 @@ public class ServletModuleLanguage extends ServletModule logger = new LoggerWrapper("ServletModule.Language"); try { - model = MirGlobal.localizer().dataModel().adapterModel(); definition = "language"; - mainModule = new ModuleLanguage(DatabaseLanguage.getInstance()); + mainModule = new ModuleLanguage(); } catch (Throwable e) { logger.error("Initialization of ServletModuleLanguage failed: " + e.getMessage()); diff --git a/source/mircoders/servlet/ServletModuleLocalizer.java b/source/mircoders/servlet/ServletModuleLocalizer.java index 26c3e4ba..39370af9 100755 --- a/source/mircoders/servlet/ServletModuleLocalizer.java +++ b/source/mircoders/servlet/ServletModuleLocalizer.java @@ -29,27 +29,22 @@ */ package mircoders.servlet; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Vector; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import mir.entity.adapter.EntityAdapter; -import mir.log.LoggerWrapper; -import mir.servlet.ServletModule; -import mir.servlet.ServletModuleExc; -import mir.util.StringRoutines; -import mircoders.entity.EntityComment; -import mircoders.entity.EntityContent; -import mircoders.entity.EntityUsers; -import mircoders.global.MirGlobal; -import mircoders.localizer.MirAdminInterfaceLocalizer; -import mircoders.module.ModuleComment; -import mircoders.module.ModuleContent; -import mircoders.storage.DatabaseComment; -import mircoders.storage.DatabaseContent; +import mir.log.LoggerWrapper; +import mir.servlet.ServletModule; +import mir.servlet.ServletModuleExc; +import mir.util.StringRoutines; +import mircoders.entity.EntityComment; +import mircoders.entity.EntityContent; +import mircoders.global.MirGlobal; +import mircoders.module.ModuleComment; +import mircoders.module.ModuleContent; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Vector; public class ServletModuleLocalizer extends ServletModule { private static ServletModuleLocalizer instance = new ServletModuleLocalizer(); @@ -63,8 +58,8 @@ public class ServletModuleLocalizer extends ServletModule { try { logger = new LoggerWrapper("ServletModule.Localizer"); - contentModule = new ModuleContent(DatabaseContent.getInstance()); - commentModule = new ModuleComment(DatabaseComment.getInstance()); + contentModule = new ModuleContent(); + commentModule = new ModuleComment(); administerOperations = new Vector(); @@ -81,8 +76,8 @@ public class ServletModuleLocalizer extends ServletModule { } else { Map entry = new HashMap(); - entry.put("name", (String) parts.get(0)); - entry.put("url", (String) parts.get(1)); + entry.put("name", parts.get(0)); + entry.put("url", parts.get(1)); administerOperations.add(entry); } } @@ -92,21 +87,28 @@ public class ServletModuleLocalizer extends ServletModule { catch (Exception e) { logger.error("ServletModuleLocalizer could not be initialized: " + e.getMessage()); } - - } - public void performCommentOperation(EntityUsers aUser, String anId, String anOperation) { - MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation; - EntityAdapter comment; + /** + * Performs a localizer operation on an article. + * + * See also + * {@link mircoders.localizer.MirAdminInterfaceLocalizer#simpleArticleOperations()} + * + * @param aRequest The originating request + * @param anId The id of the article + * @param anOperation The identifier of the operation to perform + */ + public void performCommentOperation(HttpServletRequest aRequest, String anId, String anOperation) { EntityComment entity; try { entity = (EntityComment) commentModule.getById(anId); if (entity != null) { - MirGlobal.performCommentOperation(aUser, entity, anOperation); + MirGlobal.performCommentOperation(ServletHelper.getUser(aRequest), entity, anOperation); logger.info("Operation " + anOperation + " successfully performed on comment " + anId); + logAdminUsage(aRequest, "comment."+anId, "operation " + anOperation + " performed"); } else { logger.error("Error while performing " + anOperation + " on comment " + anId + ": comment is null"); @@ -122,9 +124,9 @@ public class ServletModuleLocalizer extends ServletModule { String operationString = aRequest.getParameter("operation"); String returnUrlString = aRequest.getParameter("returnurl"); - performCommentOperation(ServletHelper.getUser(aRequest), commentIdString, operationString); + performCommentOperation(aRequest, commentIdString, operationString); - redirect(aResponse, returnUrlString); + ServletHelper.redirect(aResponse, returnUrlString); } public void commentoperationbatch(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { @@ -145,26 +147,25 @@ public class ServletModuleLocalizer extends ServletModule { String commentIdString = (String) parts.get(0); String operationString = (String) parts.get(1); - performCommentOperation(ServletHelper.getUser(aRequest), commentIdString, operationString); + performCommentOperation(aRequest, commentIdString, operationString); } } } } - redirect(aResponse, returnUrlString); + ServletHelper.redirect(aResponse, returnUrlString); } - public void performArticleOperation(EntityUsers aUser, String anId, String anOperation) { - MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation; - EntityAdapter article; + public void performArticleOperation(HttpServletRequest aRequest, String anId, String anOperation) { EntityContent entity; try { entity = (EntityContent) contentModule.getById(anId); if (entity != null) { - MirGlobal.performArticleOperation(aUser, entity, anOperation); + MirGlobal.performArticleOperation(ServletHelper.getUser(aRequest), entity, anOperation); logger.info("Operation " + anOperation + " successfully performed on article " + anId); + logAdminUsage(aRequest, "article." + anId, "operation " + anOperation + " performed"); } else { logger.error("Error while performing " + anOperation + " on article " + anId + ": article is null"); @@ -180,8 +181,8 @@ public class ServletModuleLocalizer extends ServletModule { String operationString = aRequest.getParameter("operation"); String returnUrlString = aRequest.getParameter("returnurl"); - performArticleOperation(ServletHelper.getUser(aRequest), articleIdString, operationString); - redirect(aResponse, returnUrlString); + performArticleOperation(aRequest, articleIdString, operationString); + ServletHelper.redirect(aResponse, returnUrlString); } public void articleoperationbatch(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { @@ -202,13 +203,13 @@ public class ServletModuleLocalizer extends ServletModule { String articleIdString = (String) parts.get(0); String operationString = (String) parts.get(1); - performArticleOperation(ServletHelper.getUser(aRequest), articleIdString, operationString); + performArticleOperation(aRequest, articleIdString, operationString); } } } } - redirect(aResponse, returnUrlString); + ServletHelper.redirect(aResponse, returnUrlString); } public List getAdministerOperations() throws ServletModuleExc { diff --git a/source/mircoders/servlet/ServletModuleMediaType.java b/source/mircoders/servlet/ServletModuleMediaType.java new file mode 100755 index 00000000..94007f76 --- /dev/null +++ b/source/mircoders/servlet/ServletModuleMediaType.java @@ -0,0 +1,53 @@ +/* + * 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.module.ModuleMediaType; +import mircoders.storage.DatabaseMediaType; + +public class ServletModuleMediaType extends ServletModule +{ + private static ServletModuleMediaType instance = new ServletModuleMediaType(); + public static ServletModule getInstance() { return instance; } + + private ServletModuleMediaType() { + logger = new LoggerWrapper("ServletModule.MediaType"); + + try { + definition = "mediaType"; + mainModule = new ModuleMediaType(); + } + catch (Exception e) { + logger.error("Initialization of ServletModuleArticleType failed!: " + e.getMessage()); + } + } +} diff --git a/source/mircoders/servlet/ServletModuleMediafolder.java b/source/mircoders/servlet/ServletModuleMediafolder.java index bb33dd24..4ca4ae69 100755 --- a/source/mircoders/servlet/ServletModuleMediafolder.java +++ b/source/mircoders/servlet/ServletModuleMediafolder.java @@ -1,68 +1,67 @@ -/* - * 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())); - } +/* + * 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.misc.StringUtil; +import mir.servlet.ServletModule; +import mircoders.module.ModuleMediafolder; +import mircoders.storage.DatabaseMediafolder; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.GregorianCalendar; +import java.util.Map; + +/** + * + */ +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 { + definition = "mediaFolder"; + mainModule = new ModuleMediafolder(); + } + catch (Throwable t) { + logger.error("Failed to initialize ServletModuleMediafolder: " + t.toString()); + } + } + + 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 a8ec504a..4850e527 100755 --- a/source/mircoders/servlet/ServletModuleMessage.java +++ b/source/mircoders/servlet/ServletModuleMessage.java @@ -1,77 +1,75 @@ -/* - * 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)); - } -} +/* + * 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 mir.servlet.ServletModuleFailure; +import mircoders.module.ModuleMessage; +import mircoders.storage.DatabaseMessages; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.Map; + +/** + * 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 { + definition = "internalMessage"; + mainModule = new ModuleMessage(); + } + 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 37421812..cf010d0e 100755 --- a/source/mircoders/servlet/ServletModuleOpenIndy.java +++ b/source/mircoders/servlet/ServletModuleOpenIndy.java @@ -11,7 +11,7 @@ * 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. + * GNU General Public License for more details.f * * You should have received a copy of the GNU General Public License * along with Mir; if not, write to the Free Software @@ -30,42 +30,9 @@ package mircoders.servlet; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.Locale; -import java.util.Map; -import java.util.Random; -import java.util.Set; -import java.util.Vector; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import javax.servlet.http.HttpUtils; - -import org.apache.commons.fileupload.FileItem; -import org.apache.commons.net.smtp.SMTPClient; -import org.apache.commons.net.smtp.SMTPReply; -import org.apache.lucene.analysis.standard.StandardAnalyzer; -import org.apache.lucene.document.Document; -import org.apache.lucene.queryParser.QueryParser; -import org.apache.lucene.search.Hits; -import org.apache.lucene.search.IndexSearcher; -import org.apache.lucene.search.Query; -import org.apache.lucene.search.Searcher; -import org.apache.struts.util.MessageResources; import gnu.regexp.RE; import gnu.regexp.REMatch; - +import mir.bundle.Bundle; import mir.entity.Entity; import mir.generator.Generator; import mir.log.LoggerWrapper; @@ -74,17 +41,9 @@ import mir.servlet.ServletModule; import mir.servlet.ServletModuleExc; import mir.servlet.ServletModuleFailure; import mir.servlet.ServletModuleUserExc; -import mir.session.HTTPAdapters; -import mir.session.Request; -import mir.session.Session; -import mir.session.SessionHandler; -import mir.session.SimpleResponse; -import mir.session.UploadedFile; +import mir.session.*; import mir.storage.StorageObjectFailure; -import mir.util.ExceptionFunctions; -import mir.util.HTTPParsedRequest; -import mir.util.HTTPRequestParser; -import mir.util.StringRoutines; +import mir.util.*; import mircoders.entity.EntityComment; import mircoders.entity.EntityContent; import mircoders.global.CacheKey; @@ -92,26 +51,27 @@ import mircoders.global.MirGlobal; import mircoders.media.MediaUploadProcessor; import mircoders.module.ModuleComment; import mircoders.module.ModuleContent; -import mircoders.module.ModuleImages; import mircoders.module.ModuleMediaType; -import mircoders.module.ModuleTopics; import mircoders.pdf.PDFGenerator; -import mircoders.search.AudioSearchTerm; -import mircoders.search.ContentSearchTerm; -import mircoders.search.ImagesSearchTerm; -import mircoders.search.KeywordSearchTerm; -import mircoders.search.TextSearchTerm; -import mircoders.search.TopicSearchTerm; -import mircoders.search.TopicMatrixSearchTerm; -import mircoders.search.UnIndexedSearchTerm; -import mircoders.search.VideoSearchTerm; -import mircoders.storage.DatabaseComment; -import mircoders.storage.DatabaseContent; -import mircoders.storage.DatabaseContentToMedia; -import mircoders.storage.DatabaseContentToTopics; -import mircoders.storage.DatabaseImages; -import mircoders.storage.DatabaseLanguage; -import mircoders.storage.DatabaseTopics; +import mircoders.search.*; +import mircoders.storage.*; +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.net.smtp.SMTPClient; +import org.apache.commons.net.smtp.SMTPReply; +import org.apache.lucene.analysis.standard.StandardAnalyzer; +import org.apache.lucene.document.Document; +import org.apache.lucene.index.IndexReader; +import org.apache.lucene.queryParser.QueryParser; +import org.apache.lucene.search.Hits; +import org.apache.lucene.search.IndexSearcher; +import org.apache.lucene.search.Query; +import org.apache.lucene.search.Searcher; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import java.io.*; +import java.util.*; /* * ServletModuleOpenIndy - @@ -120,7 +80,6 @@ import mircoders.storage.DatabaseTopics; * open-postings to the newswire * * @author mir-coders group - * @version $Id: ServletModuleOpenIndy.java,v 1.90 2003/09/03 18:29:05 zapata Exp $ * */ @@ -133,12 +92,12 @@ public class ServletModuleOpenIndy extends ServletModule private String prepareMailTemplate,sentMailTemplate,emailAnArticleTemplate; private ModuleContent contentModule; private ModuleComment commentModule; - private ModuleImages imageModule; - private ModuleTopics topicsModule; private String directOp ="yes"; - // Singelton / Kontruktor private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy(); - public static ServletModule getInstance() { return instance; } + + public static ServletModule getInstance() { + return instance; + } private ServletModuleOpenIndy() { super(); @@ -158,12 +117,10 @@ public class ServletModuleOpenIndy extends ServletModule emailAnArticleTemplate = configuration.getString("ServletModule.OpenIndy.MailableArticleTemplate"); sentMailTemplate = configuration.getString("ServletModule.OpenIndy.SentMailTemplate"); directOp = configuration.getString("DirectOpenposting").toLowerCase(); - commentModule = new ModuleComment(DatabaseComment.getInstance()); + commentModule = new ModuleComment(); mainModule = commentModule; - contentModule = new ModuleContent(DatabaseContent.getInstance()); - topicsModule = new ModuleTopics(DatabaseTopics.getInstance()); - imageModule = new ModuleImages(DatabaseImages.getInstance()); - defaultAction="addposting"; + contentModule = new ModuleContent(); + defaultAction = "defaultAction"; } catch (StorageObjectFailure e) { logger.error("servletmoduleopenindy could not be initialized: " + e.getMessage()); @@ -171,7 +128,14 @@ public class ServletModuleOpenIndy extends ServletModule } /** - * Method to return an "apology" when open postings are disabled + * Perform the default open posting action + */ + public void defaultAction(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { + opensession(aRequest, aResponse); + } + + /** + * Method to return an out of service notice when open postings are disabled * * @param aRequest * @param aResponse @@ -180,14 +144,12 @@ public class ServletModuleOpenIndy extends ServletModule * @throws ServletModuleFailure */ public void openPostingDisabled(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { - deliver(aRequest, aResponse, (Map) null, null, - configuration.getString("ServletModule.OpenIndy.PostingDisabledTemplate")); + deliver(aRequest, aResponse, null, null, configuration.getString("ServletModule.OpenIndy.PostingDisabledTemplate")); } /** * Method for making a comment */ - public void addcomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { if (MirGlobal.abuse().getOpenPostingDisabled()) { openPostingDisabled(req, res); @@ -203,13 +165,13 @@ public class ServletModuleOpenIndy extends ServletModule // onetimepasswd if (MirGlobal.abuse().getOpenPostingPassword()) { - String passwd = this.createOneTimePasswd(); + String passwd = generateOnetimePassword(); HttpSession session = req.getSession(false); session.setAttribute("passwd", passwd); mergeData.put("passwd", passwd); } else { - mergeData.put("passwd", (String)null); + mergeData.put("passwd", null); } mergeData.put("aid", aid); @@ -275,7 +237,7 @@ public class ServletModuleOpenIndy extends ServletModule response.setResponseGenerator(commentFormDoneTemplate); if (id == null) { - deliver(req, res, (Map)null, null, commentFormDupeTemplate); + deliver(req, res, null, null, commentFormDupeTemplate); } else { DatabaseContent.getInstance().setUnproduced("id=" + aid); @@ -309,8 +271,7 @@ public class ServletModuleOpenIndy extends ServletModule */ public void addposting(HttpServletRequest req, HttpServletResponse res) - throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure - { + throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { try { if (MirGlobal.abuse().getOpenPostingDisabled()) { openPostingDisabled(req, res); @@ -328,7 +289,7 @@ public class ServletModuleOpenIndy extends ServletModule mergeData.put("passwd", passwd); } else { - mergeData.put("passwd", (String)null); + mergeData.put("passwd", null); } String maxMedia = configuration.getString("ServletModule.OpenIndy.MaxMediaUploadItems"); @@ -356,7 +317,6 @@ public class ServletModuleOpenIndy extends ServletModule extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData()); extraInfo.put("themenPopupData", DatabaseTopics.getInstance().getPopupData()); - extraInfo.put("topics", topicsModule.getTopicsList()); deliver(req, res, mergeData, extraInfo, postingFormTemplate); } catch (Throwable t) { @@ -389,7 +349,7 @@ public class ServletModuleOpenIndy extends ServletModule HttpSession session = aRequest.getSession(false); String sessionPasswd = (String) session.getAttribute("passwd"); if (sessionPasswd != null) { - String passwd = (String) parsedRequest.getParameter("passwd"); + String passwd = parsedRequest.getParameter("passwd"); if (passwd == null || passwd.length() == 0) { throw new ServletModuleUserExc("posting.error.missingpassword", new String[] {}); @@ -400,9 +360,9 @@ public class ServletModuleOpenIndy extends ServletModule session.invalidate(); } - if ((((String) parsedRequest.getParameter("title")).length() == 0) || - (((String) parsedRequest.getParameter("description")).length() == 0) || - (((String) parsedRequest.getParameter("content_data")).length() == 0)) + if (((parsedRequest.getParameter("title")).length() == 0) || + ((parsedRequest.getParameter("description")).length() == 0) || + ((parsedRequest.getParameter("content_data")).length() == 0)) throw new ServletModuleUserExc("posting.error.missingfield", new String[] {}); List mediaList = new Vector(); @@ -524,12 +484,8 @@ public class ServletModuleOpenIndy extends ServletModule private static final String SESSION_REQUEST_KEY="sessionid"; /** - * Selects the language for the response. - * - * @param session - * @param aRequest + * Determines the Locale to be used for the current session */ - protected Locale getResponseLocale(HttpSession aSession, HttpServletRequest aRequest) { String requestLanguage = aRequest.getParameter("language"); String sessionLanguage = (String) aSession.getAttribute("language"); @@ -562,7 +518,6 @@ public class ServletModuleOpenIndy extends ServletModule * @throws ServletModuleUserExc * @throws ServletModuleFailure */ - public void opensession(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { @@ -581,7 +536,7 @@ public class ServletModuleOpenIndy extends ServletModule SimpleResponse response = new SimpleResponse( ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getResponseLocale(aRequest.getSession(), aRequest), getFallbackLocale(aRequest)}, - "bundles.open")); + "etc/bundles/open")); response.setResponseValue("actionURL", aResponse.encodeURL(MirGlobal.config().getString("RootUri") + "/servlet/OpenMir")+"?"+SESSION_REQUEST_KEY+"="+aRequest.getSession().getId()); @@ -601,7 +556,6 @@ public class ServletModuleOpenIndy extends ServletModule /** * Method for preparing and sending a content as an email message */ - public void mail(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { @@ -803,7 +757,7 @@ public class ServletModuleOpenIndy extends ServletModule session.setAttribute("positionInResults", new Integer(newPosition)); } else { - String indexPath = configuration.getString("IndexPath"); + File indexFile = FileFunctions.getAbsoluteOrRelativeFile(configuration.getHome(), configuration.getString("IndexPath")); String creatorFragment = creatorTerm.makeTerm(req); if (creatorFragment != null) { @@ -843,17 +797,17 @@ public class ServletModuleOpenIndy extends ServletModule queryString = queryString + " +" + videoFragment; } - if (queryString == null || queryString == "") { + if (queryString == null || queryString.length()==0) { queryString = ""; } else { try { Searcher searcher = null; try { - searcher = new IndexSearcher(indexPath); + searcher = new IndexSearcher(IndexReader.open(indexFile)); } catch (IOException e) { - logger.debug("Can't open indexPath: " + indexPath); + logger.debug("Can't open indexPath: " + indexFile.getAbsolutePath()); throw new ServletModuleExc("Problem with Search Index! : " + e.toString()); } @@ -958,7 +912,7 @@ public class ServletModuleOpenIndy extends ServletModule ArrayList theDocs = (ArrayList) session.getAttribute("theDocumentsSorted"); if (theDocs != null) { - mergeData.put("numberOfHits", ( (Integer) session.getAttribute("numberOfHits")).toString()); + mergeData.put("numberOfHits", (session.getAttribute("numberOfHits")).toString()); List theHits = new Vector(); int pIR = ( (Integer) session.getAttribute("positionInResults")).intValue(); int terminus; @@ -1019,83 +973,80 @@ public class ServletModuleOpenIndy extends ServletModule */ public void getpdf(HttpServletRequest req, HttpServletResponse res) - throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { - long starttime=System.currentTimeMillis(); + throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { + long starttime = System.currentTimeMillis(); String ID_REQUEST_PARAM = "id"; int maxArticlesInNewsleter = 15; // it is nice not to be dos'ed try { String idParam = req.getParameter(ID_REQUEST_PARAM); if (idParam != null) { + RE re = new RE("[0-9]+"); - RE re = new RE("[0-9]+"); - + REMatch[] idMatches = re.getAllMatches(idParam); - REMatch[] idMatches=re.getAllMatches(idParam); + String cacheSelector = ""; - String cacheSelector=""; - - for (int i = 0; i < idMatches.length; i++){ - cacheSelector= cacheSelector + "," + idMatches[i].toString(); - } + for (int i = 0; i < idMatches.length; i++) { + cacheSelector = cacheSelector + "," + idMatches[i].toString(); + } - String cacheType="pdf"; + String cacheType = "pdf"; - CacheKey theCacheKey = new CacheKey(cacheType,cacheSelector); + CacheKey theCacheKey = new CacheKey(cacheType, cacheSelector); - byte[] thePDF; + byte[] thePDF; - if (MirGlobal.mruCache().hasObject(theCacheKey)){ - logger.info("fetching pdf from cache"); - thePDF = (byte[]) MirGlobal.mruCache().getObject(theCacheKey); - } - else { - logger.info("generating pdf and caching it"); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - PDFGenerator pdfMaker = new PDFGenerator(out); - - if (idMatches.length > 1){ - pdfMaker.addLine(); - for (int i = 0; i < idMatches.length && i < maxArticlesInNewsleter; i++){ - REMatch aMatch = idMatches[i]; - String id=aMatch.toString(); - EntityContent contentEnt = (EntityContent)contentModule.getById(id); - pdfMaker.addIndexItem(contentEnt); - } - } + if (MirGlobal.mruCache().hasObject(theCacheKey)) { + logger.info("fetching pdf from cache"); + thePDF = (byte[]) MirGlobal.mruCache().getObject(theCacheKey); + } + else { + logger.info("generating pdf and caching it"); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + PDFGenerator pdfMaker = new PDFGenerator(out); + + if (idMatches.length > 1) { + pdfMaker.addLine(); + for (int i = 0; i < idMatches.length && i < maxArticlesInNewsleter; i++) { + REMatch aMatch = idMatches[i]; + String id = aMatch.toString(); + EntityContent contentEnt = (EntityContent) contentModule.getById(id); + pdfMaker.addIndexItem(contentEnt); + } + } - for (int i = 0; i < idMatches.length; i++){ - REMatch aMatch = idMatches[i]; - String id=aMatch.toString(); - EntityContent contentEnt = (EntityContent)contentModule.getById(id); + for (int i = 0; i < idMatches.length; i++) { + REMatch aMatch = idMatches[i]; + String id = aMatch.toString(); + EntityContent contentEnt = (EntityContent) contentModule.getById(id); - pdfMaker.add(contentEnt); - } + pdfMaker.add(contentEnt); + } - pdfMaker.stop(); - thePDF = out.toByteArray(); + pdfMaker.stop(); + thePDF = out.toByteArray(); - //and save all our hard work! - MirGlobal.mruCache().storeObject(theCacheKey,thePDF); - } + //and save all our hard work! + MirGlobal.mruCache().storeObject(theCacheKey, thePDF); + } - res.setContentType("application/pdf"); - res.setContentLength(thePDF.length); - res.getOutputStream().write(thePDF); - res.getOutputStream().flush(); - String elapsedtime=(new Long(System.currentTimeMillis()-starttime)).toString(); - logger.info("pdf retireval took "+elapsedtime + " milliseconds" ); + res.setContentType("application/pdf"); + res.setContentLength(thePDF.length); + res.getOutputStream().write(thePDF); + res.getOutputStream().flush(); + String elapsedtime = (new Long(System.currentTimeMillis() - starttime)).toString(); + logger.info("pdf retireval took " + elapsedtime + " milliseconds"); } else { - throw new ServletModuleExc("Missing id."); + throw new ServletModuleExc("Missing id."); } } catch (Throwable t) { logger.error(t.toString()); throw new ServletModuleFailure(t); } - } @@ -1126,7 +1077,7 @@ public class ServletModuleOpenIndy extends ServletModule public void deliver(PrintWriter anOutputWriter, HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator) throws ServletModuleFailure { try { - Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}, "bundles.open"); + Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}, "etc/bundles/open"); responseData.put("data", aData); responseData.put("extra", anExtra); @@ -1146,7 +1097,7 @@ public class ServletModuleOpenIndy extends ServletModule public void deliver(PrintWriter anOutputWriter, HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator,String aLocaleString) throws ServletModuleFailure { try { - Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { new Locale(aLocaleString,""), getFallbackLocale(aRequest)}, "bundles.open"); + Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { new Locale(aLocaleString,""), getFallbackLocale(aRequest)}, "etc/bundles/open"); responseData.put("data", aData); responseData.put("extra", anExtra); @@ -1185,8 +1136,10 @@ public class ServletModuleOpenIndy extends ServletModule logger.warn("user error: " + anException.getMessage()); Map data = new HashMap(); - MessageResources messages = MessageResources.getMessageResources("bundles.open"); - data.put("errorstring", messages.getMessage(getLocale(aRequest), anException.getMessage(), anException.getParameters())); + Bundle bundle = + MirGlobal.getBundleFactory().getBundle("etc/bundles/open", new + String[] { getLocale(aRequest).getLanguage() }); + data.put("errorstring", bundle.getValue(anException.getMessage(), Arrays.asList(anException.getParameters()))); data.put("date", StringUtil.date2readableDateTime(new GregorianCalendar())); deliver(out, aRequest, aResponse, data, null, configuration.getString("ServletModule.OpenIndy.UserErrorTemplate")); @@ -1195,8 +1148,4 @@ public class ServletModuleOpenIndy extends ServletModule throw new ServletModuleFailure(e); } } - - private String createOneTimePasswd() { - return ""; - } } diff --git a/source/mircoders/servlet/ServletModuleOtherMedia.java b/source/mircoders/servlet/ServletModuleOtherMedia.java index 09406964..d447c098 100755 --- a/source/mircoders/servlet/ServletModuleOtherMedia.java +++ b/source/mircoders/servlet/ServletModuleOtherMedia.java @@ -32,10 +32,8 @@ package mircoders.servlet; import mir.log.LoggerWrapper; import mir.servlet.ServletModule; -import mir.storage.StorageObjectFailure; import mircoders.module.ModuleUploadedMedia; import mircoders.storage.DatabaseOther; -import mircoders.global.*; /** * @@ -60,7 +58,6 @@ public class ServletModuleOtherMedia extends ServletModuleUploadedMedia { moduleName = "OtherMedia"; try { - model = MirGlobal.localizer().dataModel().adapterModel(); definition = "otherMedia"; mainModule = new ModuleUploadedMedia(DatabaseOther.getInstance()); } diff --git a/source/mircoders/servlet/ServletModuleProducer.java b/source/mircoders/servlet/ServletModuleProducer.java index 26af5336..f6e3b67a 100755 --- a/source/mircoders/servlet/ServletModuleProducer.java +++ b/source/mircoders/servlet/ServletModuleProducer.java @@ -29,7 +29,9 @@ */ package mircoders.servlet; +import java.io.IOException; import java.io.PrintWriter; +import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; @@ -39,15 +41,12 @@ import java.util.Vector; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.apache.struts.util.MessageResources; - import mir.generator.Generator; import mir.log.LoggerWrapper; import mir.producer.ProducerFactory; import mir.servlet.ServletModule; import mir.servlet.ServletModuleFailure; import mir.util.HTTPRequestParser; -import mir.util.ResourceBundleGeneratorFunction; import mircoders.global.MirGlobal; public class ServletModuleProducer extends ServletModule @@ -56,22 +55,8 @@ public class ServletModuleProducer extends ServletModule public static ServletModule getInstance() { return instance; } Object comments; - Map generationData; - Generator generator; int totalNrComments; - List producersData; - void generateResponse(String aGeneratorIdentifier, PrintWriter aWriter, Map aResponseData, Locale aLocale) { - try { - generator = MirGlobal.localizer().generators().makeAdminGeneratorLibrary().makeGenerator(aGeneratorIdentifier); - MirGlobal.localizer().producerAssistant().initializeGenerationValueSet(aResponseData); - aResponseData.put( "lang", new ResourceBundleGeneratorFunction( aLocale, MessageResources.getMessageResources("bundles.admin"))); - generator.generate(aWriter, aResponseData, logger); - } - catch (Throwable t) { - throw new ServletModuleFailure(t); - } - } private ServletModuleProducer() { super(); @@ -79,42 +64,30 @@ public class ServletModuleProducer extends ServletModule defaultAction="showProducerQueueStatus"; } - public void showMessage(HttpServletRequest aRequest, HttpServletResponse aResponse, String aMessage, String anArgument1, String anArgument2) { - Map responseData; - try { - responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}); - responseData.put("message", aMessage); - responseData.put("argument1", anArgument1); - responseData.put("argument2", anArgument2); - - ServletHelper.generateResponse(aResponse.getWriter(), responseData, "infomessage.template"); - } - catch (Throwable t) { - throw new ServletModuleFailure(t); - } - } - - + /** + * + * @param aRequest + * @param aResponse + */ public void showProducerQueueStatus(HttpServletRequest aRequest, HttpServletResponse aResponse) { - Object comments; Map generationData; Generator generator; - int totalNrComments; List producersData; try { + // TODO: use ServletHelper generator = MirGlobal.localizer().generators().makeAdminGeneratorLibrary().makeGenerator("producerqueue.template"); generationData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}); generationData.put( "thisurl", "module=Producer&do=showProducerQueueStatus"); producersData = new Vector(); - Iterator i = MirGlobal.localizer().producers().factories().iterator(); + Iterator i = MirGlobal.getProducerEngine().getFactories().iterator(); while (i.hasNext()) { ProducerFactory factory = (ProducerFactory) i.next(); List producerVerbs = new Vector(); - Iterator j = factory.verbs(); + Iterator j = factory.verbs().iterator(); while (j.hasNext()) { Map verbData = new HashMap(); ProducerFactory.ProducerVerb verb = (ProducerFactory.ProducerVerb) j.next(); @@ -132,7 +105,7 @@ public class ServletModuleProducer extends ServletModule } generationData.put("producers", producersData); - generationData.put("queue", MirGlobal.producerEngine().getQueueStatus()); + generationData.put("queue", MirGlobal.getProducerEngine().getQueueStatus()); generator.generate(aResponse.getWriter(), generationData, logger); } catch (Throwable t) { @@ -140,13 +113,11 @@ public class ServletModuleProducer extends ServletModule } } + /** + * This method will only be called by external scripts (e.g. from cron jobs). + * The output therefore is very simple. + */ public void produce(HttpServletRequest aRequest, HttpServletResponse aResponse) { - /* - * This method will only be called by external scripts (e.g. from cron jobs). - * The output therefore is very simple. - * - */ - try { PrintWriter out = aResponse.getWriter(); @@ -154,32 +125,48 @@ public class ServletModuleProducer extends ServletModule String producerParam = aRequest.getParameter("producer"); String verbParam = aRequest.getParameter("verb"); - MirGlobal.producerEngine().addJob(producerParam, verbParam); - out.println("job added"); + try { + MirGlobal.getProducerEngine().addJob(producerParam, verbParam); + out.println("job added"); + } + catch (Throwable t) { + out.println("Can't add job: " + t.getMessage()); + } } } - catch (Throwable t) { - throw new ServletModuleFailure(t); + catch (IOException e) { + throw new ServletModuleFailure(e); } } - public void produceAllNew(HttpServletRequest aRequest, HttpServletResponse aResponse) { + /** + * Servlet action to propduce a preconfigured combination of producers + * (e.g. "generate all new") + */ + public void producerecipe(HttpServletRequest aRequest, HttpServletResponse aResponse) { try { - MirGlobal.localizer().producers().produceAllNew(); - showMessage(aRequest, aResponse, "produceAllNewAddedToQueue", "", ""); + String recipe = aRequest.getParameter("recipe"); + MirGlobal.localizer().producers().produceRecipe(recipe); + + ServletHelper.generateInfoMessage(aRequest, aResponse, + new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}, + "bundles/admin", "etc/bundles/adminlocal", "recipeAddedToQueue", recipe, ""); } catch (Throwable t) { throw new ServletModuleFailure(t); } } + /** + * Servlet action to enqueue a producer job + */ public void enqueue(HttpServletRequest aRequest, HttpServletResponse aResponse) { try { if (aRequest.getParameter("producer")!=null) { String producerParam = aRequest.getParameter("producer"); String verbParam = aRequest.getParameter("verb"); - MirGlobal.producerEngine().addJob(producerParam, verbParam); + MirGlobal.getProducerEngine().addJob(producerParam, verbParam); ServletHelper.redirect(aResponse, "Producer", "showProducerQueueStatus"); } @@ -192,9 +179,15 @@ public class ServletModuleProducer extends ServletModule public void cancel(HttpServletRequest aRequest, HttpServletResponse aResponse) { try { HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - List jobs = new Vector(requestParser.getParameterList("jobid")); - MirGlobal.producerEngine().cancelJobs(jobs); + if (requestParser.getParameter("cancelall") != null) { + MirGlobal.getProducerEngine().cancelAllJobs(); + } + else { + List jobs = new ArrayList(requestParser.getParameterList("jobid")); + + MirGlobal.getProducerEngine().cancelJobs(jobs); + } ServletHelper.redirect(aResponse, "Producer", "showProducerQueueStatus"); } catch (Throwable t) { diff --git a/source/mircoders/servlet/ServletModuleTopics.java b/source/mircoders/servlet/ServletModuleTopics.java index 63fdd7c9..e7700d0e 100755 --- a/source/mircoders/servlet/ServletModuleTopics.java +++ b/source/mircoders/servlet/ServletModuleTopics.java @@ -32,19 +32,10 @@ package mircoders.servlet; import mir.log.LoggerWrapper; import mir.servlet.ServletModule; -import mir.storage.StorageObjectFailure; import mircoders.module.ModuleTopics; -import mircoders.storage.DatabaseTopics; -import mircoders.global.*; /** * - *

Title:

- *

Description:

- *

Copyright: Copyright (c) 2003

- *

Company:

- * @author not attributable - * @version 1.0 */ public class ServletModuleTopics extends ServletModule @@ -57,9 +48,8 @@ public class ServletModuleTopics extends ServletModule logger = new LoggerWrapper("ServletModule.Topics"); try { - model = MirGlobal.localizer().dataModel().adapterModel(); definition = "topic"; - mainModule = new ModuleTopics(DatabaseTopics.getInstance()); + mainModule = new ModuleTopics(); } 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 6dddfa73..e1559f3c 100755 --- a/source/mircoders/servlet/ServletModuleUploadedMedia.java +++ b/source/mircoders/servlet/ServletModuleUploadedMedia.java @@ -1,507 +1,574 @@ -/* - * 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.InputStream; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Vector; -import javax.servlet.ServletContext; -import javax.servlet.ServletOutputStream; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.fileupload.FileItem; -import mir.config.MirPropertiesConfiguration; -import mir.entity.Entity; -import mir.entity.adapter.EntityAdapter; -import mir.entity.adapter.EntityAdapterModel; -import mir.entity.adapter.EntityIteratorAdapter; -import mir.log.LoggerWrapper; -import mir.media.MediaHelper; -import mir.media.MirMedia; -import mir.servlet.ServletModule; -import mir.servlet.ServletModuleExc; -import mir.servlet.ServletModuleFailure; -import mir.servlet.ServletModuleUserExc; -import mir.session.UploadedFile; -import mir.util.CachingRewindableIterator; -import mir.util.ExceptionFunctions; -import mir.util.HTTPParsedRequest; -import mir.util.HTTPRequestParser; -import mir.util.JDBCStringRoutines; -import mir.util.SQLQueryBuilder; -import mir.util.URLBuilder; -import mircoders.entity.EntityComment; -import mircoders.entity.EntityContent; -import mircoders.entity.EntityUploadedMedia; -import mircoders.global.MirGlobal; -import mircoders.media.MediaUploadProcessor; -import mircoders.module.ModuleMediaType; -import mircoders.storage.DatabaseComment; -import mircoders.storage.DatabaseContent; - -/** - * - *

Title:

- *

Description:

- *

Copyright: Copyright (c) 2003

- *

Company:

- * @author the mir coders - * @version 1.0 - */ - -public abstract class ServletModuleUploadedMedia extends ServletModule { - protected String moduleName = "UploadedMedia"; - - public static ServletModule getInstance() { - return null; - } - - 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) - throws ServletModuleExc, ServletModuleUserExc { - try { - HTTPParsedRequest parsedRequest = new HTTPParsedRequest(aRequest, - configuration.getString("Mir.DefaultEncoding"), - configuration.getInt("MaxMediaUploadSize")*1024, - configuration.getString("TempDir")); - - Map mediaValues = new HashMap(); - - mediaValues.put("to_publisher", ServletHelper.getUser(aRequest).getId()); - - Iterator i = mainModule.getStorageObject().getFields().iterator(); - while (i.hasNext()) { - String field = (String) i.next(); - String value = parsedRequest.getParameter(field); - if (value!=null) - mediaValues.put(field, value); - } - - List mediaList = new Vector(); - - i = parsedRequest.getFiles().iterator(); - while (i.hasNext()) { - UploadedFile file = new mir.session.CommonsUploadedFileAdapter((FileItem) i.next()); - - String suffix = file.getFieldName().substring(5); - mediaValues.put("title", parsedRequest.getParameter("media_title" + suffix)); - - mediaList.add(MediaUploadProcessor.processMediaUpload(file, mediaValues)); - } - - String articleid = parsedRequest.getParameter("articleid"); - String commentid = parsedRequest.getParameter("commentid"); - - if (articleid!=null) { - EntityContent entContent = (EntityContent) DatabaseContent.getInstance().selectById(articleid); - - i=mediaList.iterator(); - - while (i.hasNext()) { - entContent.attach(((EntityUploadedMedia) i.next()).getId()); - } - - ((ServletModuleContent) ServletModuleContent.getInstance())._showObject(articleid, aRequest, aResponse); - - return; - } - - if (commentid!=null) { - EntityComment comment = (EntityComment) DatabaseComment.getInstance().selectById(commentid); - - i=mediaList.iterator(); - - while (i.hasNext()) { - comment.attach( ( (EntityUploadedMedia) i.next()).getId()); - } - - ((ServletModuleComment) ServletModuleComment.getInstance()).showComment(commentid, aRequest, aResponse); - - return; - } - - returnUploadedMediaList(aRequest, aResponse, mediaList, 1, mediaList.size(), mediaList.size(), "", null, null); - } - catch (Throwable t) { - Throwable cause = ExceptionFunctions.traceCauseException(t); - - if (cause instanceof ModuleMediaType.UnsupportedMimeTypeExc) { - throw new ServletModuleUserExc("media.error.unsupportedformat", new String[] {}); - } - throw new ServletModuleFailure("ServletModuleUploadedMedia.insert: " + t.toString(), t); - } - } - - public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { - - try { - HTTPParsedRequest parsedRequest = new HTTPParsedRequest(aRequest, - configuration.getString("Mir.DefaultEncoding"), - configuration.getInt("MaxMediaUploadSize")*1024, - configuration.getString("TempDir")); - Map mediaValues = new HashMap(); - - Iterator i = mainModule.getStorageObject().getFields().iterator(); - while (i.hasNext()) { - String field = (String) i.next(); - String value = parsedRequest.getParameter(field); - if (value!=null) - mediaValues.put(field, value); - } - - mediaValues.put("to_publisher", ServletHelper.getUser(aRequest).getId()); - mediaValues.put("is_produced", "0"); - if (!mediaValues.containsKey("is_published")) - mediaValues.put("is_published", "0"); - - String id = mainModule.set(mediaValues); - logger.debug("update: media ID = " + id); - - editUploadedMediaObject(id, aRequest, aResponse); - } - catch (Throwable e) { - throw new ServletModuleFailure("upload -- exception " + e.toString(), e); - } - - } - - public void returnUploadedMediaList(HttpServletRequest aRequest, HttpServletResponse aResponse, - Object aList, int aFrom, int aTo, int aCount, - String aThisUrl, String aNextUrl, String aPreviousUrl) throws ServletModuleExc { - - try { - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)}); - - responseData.put("searchfield", requestParser.getParameterWithDefault("searchfield", "")); - responseData.put("searchtext", requestParser.getParameterWithDefault("searchtext", "")); - responseData.put("searchispublished", requestParser.getParameterWithDefault("searchispublished", "")); - responseData.put("searchmediafolder", requestParser.getParameterWithDefault("searchmediafolder", "")); - responseData.put("articleid", requestParser.getParameter("articleid")); - responseData.put("commentid", requestParser.getParameter("commentid")); - - responseData.put("thisurl", aThisUrl); - responseData.put("nexturl", aNextUrl); - responseData.put("prevurl", aPreviousUrl); - - responseData.put("from", Integer.toString(aFrom)); - responseData.put("count", Integer.toString(aCount)); - responseData.put("to", Integer.toString(aTo)); - - responseData.put("medialist", aList); - - addExtraData(responseData); - ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator); - } - catch (Throwable t) { - throw new ServletModuleFailure(t); - } - } - - public void returnUploadedMediaList(HttpServletRequest aRequest, HttpServletResponse aResponse, - String aWhereClause, String anOrderByClause, int anOffset) throws ServletModuleExc { - - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - URLBuilder urlBuilder = new URLBuilder(); - EntityAdapterModel model; - String nextPageUrl = null; - String previousPageUrl = null; - String thisUrl = null; - - int count; - - try { - model = MirGlobal.localizer().dataModel().adapterModel(); - - Object mediaList = - new CachingRewindableIterator( - new EntityIteratorAdapter(aWhereClause, anOrderByClause, nrEntitiesPerListPage, - model, definition, nrEntitiesPerListPage, anOffset) - ); - - count = mainModule.getSize(aWhereClause); - - urlBuilder.setValue("module", moduleName); - urlBuilder.setValue("do", "list"); - urlBuilder.setValue("where", aWhereClause); - urlBuilder.setValue("order", anOrderByClause); - - urlBuilder.setValue("articleid", requestParser.getParameter("articleid")); - urlBuilder.setValue("commentid", requestParser.getParameter("commentid")); - urlBuilder.setValue("searchfield", requestParser.getParameter("searchfield")); - urlBuilder.setValue("searchtext", requestParser.getParameter("searchtext")); - urlBuilder.setValue("searchispublished", requestParser.getParameter("searchispublished")); - urlBuilder.setValue("searchmediafolder", requestParser.getParameter("searchmediafolder")); - urlBuilder.setValue("where", aWhereClause); - urlBuilder.setValue("order", anOrderByClause); - - urlBuilder.setValue("offset", anOffset); - thisUrl = urlBuilder.getQuery(); - - if (count >= anOffset + nrEntitiesPerListPage) { - urlBuilder.setValue("offset", anOffset + nrEntitiesPerListPage); - nextPageUrl = urlBuilder.getQuery(); - } - - if (anOffset > 0) { - urlBuilder.setValue("offset", Math.max(anOffset - nrEntitiesPerListPage, 0)); - previousPageUrl = urlBuilder.getQuery(); - } - - returnUploadedMediaList(aRequest, aResponse, mediaList, - anOffset+1, anOffset+nrEntitiesPerListPage, count, thisUrl, - nextPageUrl, previousPageUrl); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - public void search(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - - SQLQueryBuilder queryBuilder = new SQLQueryBuilder(); - - String queryField = ""; - String searchField = requestParser.getParameter("searchfield"); - String searchText = requestParser.getParameter("searchtext"); - String searchIsPublished = requestParser.getParameter("searchispublished"); - String searchMediaFolder = requestParser.getParameter("searchmediafolder"); - - queryBuilder.appendDescendingOrder("webdb_create"); - - if (searchIsPublished!=null) - if (searchIsPublished.equals("0")) { - queryBuilder.appendAndCondition("is_published='f'"); - } - else if (searchIsPublished.equals("1")) { - queryBuilder.appendAndCondition("is_published='t'"); - } - - if (searchField!=null && searchText!=null && searchText.length()>0) { - queryBuilder.appendAndCondition( - "lower(" + searchField + ") like " + - "'%" + JDBCStringRoutines.escapeStringLiteral(searchText.toLowerCase()) + "%'"); - } - - if (searchMediaFolder!=null && searchMediaFolder.length()>0) { - queryBuilder.appendAndCondition("to_media_folder="+Integer.parseInt(searchMediaFolder)); - } - - returnUploadedMediaList(aRequest, aResponse, - queryBuilder.getWhereClause(), queryBuilder.getOrderByClause(), requestParser.getIntegerWithDefault("offset", 0)); - } - - public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - - returnUploadedMediaList(aRequest, aResponse, - requestParser.getParameterWithDefault("where", ""), - requestParser.getParameterWithDefault("order", "webdb_create desc"), - requestParser.getIntegerWithDefault("offset", 0)); - } - - - public void add(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { - try { - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)}); - - int nrMedia = requestParser.getIntegerWithDefault("nrmedia", 1); - int maxNrMedia=configuration.getInt("ServletModule.OpenIndy.MaxMediaUploadItems", 20); - - List fields = mainModule.getStorageObject().getFields(); - Map media = new HashMap(); - Iterator i = fields.iterator(); - while (i.hasNext()) { - media.put(i.next(), null); - } - media.put("to_media_folder", new Integer(7)); - responseData.put("uploadedmedia", media); - - responseData.put("new", Boolean.TRUE); - responseData.put("articleid", requestParser.getParameter("articleid")); - responseData.put("commentid", requestParser.getParameter("commentid")); - responseData.put("returnurl", null); - - if (nrMedia<=0) - nrMedia=1; - if (nrMedia>maxNrMedia) - nrMedia=maxNrMedia; - - List mediaFields = new Vector(); - for (int j=0; jTitle:

+ *

Description:

+ *

Copyright: Copyright (c) 2003

+ *

Company:

+ * @author the mir coders + * @version 1.0 + */ + +public abstract class ServletModuleUploadedMedia extends ServletModule { + protected String moduleName = "UploadedMedia"; + + public static ServletModule getInstance() { + return null; + } + + public ServletModuleUploadedMedia() { + super(); + + definition = "uploadedMedia"; + logger = new LoggerWrapper("ServletModule.UploadedMedia"); + } + + public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse) + throws ServletModuleExc, ServletModuleUserExc { + try { + HTTPParsedRequest parsedRequest = new HTTPParsedRequest(aRequest, + configuration.getString("Mir.DefaultEncoding"), + configuration.getInt("MaxMediaUploadSize")*1024, + configuration.getString("TempDir")); + + Map mediaValues = new HashMap(); + + mediaValues.put("to_publisher", ServletHelper.getUser(aRequest).getId()); + + Iterator i = mainModule.getStorageObject().getFields().iterator(); + while (i.hasNext()) { + String field = (String) i.next(); + String value = parsedRequest.getParameter(field); + if (value!=null) + mediaValues.put(field, value); + } + + List mediaList = new ArrayList(); + + i = parsedRequest.getFiles().iterator(); + while (i.hasNext()) { + UploadedFile file = new mir.session.CommonsUploadedFileAdapter((FileItem) i.next()); + + String suffix = file.getFieldName().substring(5); + mediaValues.put("title", parsedRequest.getParameter("media_title" + suffix)); + + mediaList.add(MediaUploadProcessor.processMediaUpload(file, mediaValues)); + } + + String articleid = parsedRequest.getParameter("articleid"); + String commentid = parsedRequest.getParameter("commentid"); + + if (articleid!=null) { + EntityContent entContent = (EntityContent) DatabaseContent.getInstance().selectById(articleid); + + i=mediaList.iterator(); + + while (i.hasNext()) { + String id = ((EntityUploadedMedia) i.next()).getId(); + + entContent.attach(id); + logAdminUsage(aRequest, id, "object attached to article " + articleid); + } + + (ServletModuleContent.getInstance()).editObject(aRequest, aResponse, articleid); + + + return; + } + + if (commentid!=null) { + EntityComment comment = (EntityComment) DatabaseComment.getInstance().selectById(commentid); + + i=mediaList.iterator(); + + while (i.hasNext()) { + String id = ((EntityUploadedMedia) i.next()).getId(); + + comment.attach(id); + + logAdminUsage(aRequest, id, "object attached to comment " + commentid); + } + + (ServletModuleComment.getInstance()).editObject(aRequest, aResponse, commentid); + + return; + } + + logAdminUsage(aRequest, "", mediaList.size() + " objects added"); + + returnUploadedMediaList(aRequest, aResponse, mediaList, 1, mediaList.size(), mediaList.size(), "", null, null); + } + catch (Throwable t) { + Throwable cause = ExceptionFunctions.traceCauseException(t); + + if (cause instanceof ModuleMediaType.UnsupportedMimeTypeExc) { + throw new ServletModuleUserExc("media.error.unsupportedformat", new String[] {}); + } + throw new ServletModuleFailure("ServletModuleUploadedMedia.insert: " + t.toString(), t); + } + } + + public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { + + try { + HTTPParsedRequest parsedRequest = new HTTPParsedRequest(aRequest, + configuration.getString("Mir.DefaultEncoding"), + configuration.getInt("MaxMediaUploadSize")*1024, + configuration.getString("TempDir")); + Map mediaValues = new HashMap(); + + Iterator i = mainModule.getStorageObject().getFields().iterator(); + while (i.hasNext()) { + String field = (String) i.next(); + String value = parsedRequest.getParameter(field); + if (value!=null) + mediaValues.put(field, value); + } + + mediaValues.put("to_publisher", ServletHelper.getUser(aRequest).getId()); + mediaValues.put("is_produced", "0"); + if (!mediaValues.containsKey("is_published")) + mediaValues.put("is_published", "0"); + + String id = mainModule.set(mediaValues); + logger.debug("update: media ID = " + id); + logAdminUsage(aRequest, id, "object modified"); + + editUploadedMediaObject(id, aRequest, aResponse); + } + catch (Throwable e) { + throw new ServletModuleFailure("upload -- exception " + e.toString(), e); + } + + } + + public void returnUploadedMediaList(HttpServletRequest aRequest, HttpServletResponse aResponse, + Object aList, int aFrom, int aTo, int aCount, + String aThisUrl, String aNextUrl, String aPreviousUrl) throws ServletModuleExc { + + try { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)}); + + responseData.put("searchfield", requestParser.getParameterWithDefault("searchfield", "")); + responseData.put("searchtext", requestParser.getParameterWithDefault("searchtext", "")); + responseData.put("searchispublished", requestParser.getParameterWithDefault("searchispublished", "")); + responseData.put("searchmediafolder", requestParser.getParameterWithDefault("searchmediafolder", "")); + responseData.put("articleid", requestParser.getParameter("articleid")); + responseData.put("commentid", requestParser.getParameter("commentid")); + + responseData.put("thisurl", aThisUrl); + responseData.put("nexturl", aNextUrl); + responseData.put("prevurl", aPreviousUrl); + responseData.put("returnurl", requestParser.getParameter("returnurl")); + + + responseData.put("from", Integer.toString(aFrom)); + responseData.put("count", Integer.toString(aCount)); + responseData.put("to", Integer.toString(aTo)); + + responseData.put("medialist", aList); + + addExtraData(responseData); + ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator); + } + catch (Throwable t) { + throw new ServletModuleFailure(t); + } + } + + public void returnUploadedMediaList(HttpServletRequest aRequest, HttpServletResponse aResponse, + String aWhereClause, String anOrderByClause, int anOffset) throws ServletModuleExc { + + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + URLBuilder urlBuilder = new URLBuilder(); + EntityAdapterModel model; + String nextPageUrl = null; + String previousPageUrl = null; + String thisUrl = null; + + int count; + + try { + model = MirGlobal.localizer().dataModel().adapterModel(); + + Object mediaList = + new CachingRewindableIterator( + new EntityIteratorAdapter(aWhereClause, anOrderByClause, nrEntitiesPerListPage, + model, definition, nrEntitiesPerListPage, anOffset) + ); + + count = mainModule.getSize(aWhereClause); + + urlBuilder.setValue("module", moduleName); + urlBuilder.setValue("do", "list"); + urlBuilder.setValue("where", aWhereClause); + urlBuilder.setValue("order", anOrderByClause); + + urlBuilder.setValue("articleid", requestParser.getParameter("articleid")); + urlBuilder.setValue("commentid", requestParser.getParameter("commentid")); + urlBuilder.setValue("searchfield", requestParser.getParameter("searchfield")); + urlBuilder.setValue("searchtext", requestParser.getParameter("searchtext")); + urlBuilder.setValue("searchispublished", requestParser.getParameter("searchispublished")); + urlBuilder.setValue("searchmediafolder", requestParser.getParameter("searchmediafolder")); + urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl")); + urlBuilder.setValue("where", aWhereClause); + urlBuilder.setValue("order", anOrderByClause); + + urlBuilder.setValue("offset", anOffset); + thisUrl = urlBuilder.getQuery(); + + if (count >= anOffset + nrEntitiesPerListPage) { + urlBuilder.setValue("offset", anOffset + nrEntitiesPerListPage); + nextPageUrl = urlBuilder.getQuery(); + } + + if (anOffset > 0) { + urlBuilder.setValue("offset", Math.max(anOffset - nrEntitiesPerListPage, 0)); + previousPageUrl = urlBuilder.getQuery(); + } + + returnUploadedMediaList(aRequest, aResponse, mediaList, + anOffset+1, anOffset+nrEntitiesPerListPage, count, thisUrl, + nextPageUrl, previousPageUrl); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + public void search(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + + SQLQueryBuilder queryBuilder = new SQLQueryBuilder(); + + String searchField = requestParser.getParameter("searchfield"); + String searchText = requestParser.getParameter("searchtext"); + String searchIsPublished = requestParser.getParameter("searchispublished"); + String searchMediaFolder = requestParser.getParameter("searchmediafolder"); + + queryBuilder.appendDescendingOrder("webdb_create"); + + if (searchIsPublished!=null) + if (searchIsPublished.equals("0")) { + queryBuilder.appendAndCondition("is_published='f'"); + } + else if (searchIsPublished.equals("1")) { + queryBuilder.appendAndCondition("is_published='t'"); + } + + if (searchField!=null && searchText!=null && searchText.length()>0) { + queryBuilder.appendAndCondition( + "lower(" + searchField + ") like " + + "'%" + JDBCStringRoutines.escapeStringLiteral(searchText.toLowerCase()) + "%'"); + } + + if (searchMediaFolder!=null && searchMediaFolder.length()>0) { + queryBuilder.appendAndCondition("to_media_folder="+Integer.parseInt(searchMediaFolder)); + } + + returnUploadedMediaList(aRequest, aResponse, + queryBuilder.getWhereClause(), queryBuilder.getOrderByClause(), requestParser.getIntegerWithDefault("offset", 0)); + } + + public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + + returnUploadedMediaList(aRequest, aResponse, + requestParser.getParameterWithDefault("where", ""), + requestParser.getParameterWithDefault("order", "webdb_create desc"), + requestParser.getIntegerWithDefault("offset", 0)); + } + + + public void add(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { + try { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)}); + + int nrMedia = requestParser.getIntegerWithDefault("nrmedia", 1); + int maxNrMedia=configuration.getInt("ServletModule.OpenIndy.MaxMediaUploadItems", 20); + + List fields = mainModule.getStorageObject().getFields(); + Map media = new HashMap(); + Iterator i = fields.iterator(); + while (i.hasNext()) { + media.put(i.next(), null); + } + media.put("to_media_folder", new Integer(7)); + responseData.put("uploadedmedia", media); + + responseData.put("new", Boolean.TRUE); + responseData.put("articleid", requestParser.getParameter("articleid")); + responseData.put("commentid", requestParser.getParameter("commentid")); + responseData.put("returnurl", requestParser.getParameter("returnurl")); + + if (nrMedia<=0) + nrMedia=1; + if (nrMedia>maxNrMedia) + nrMedia=maxNrMedia; + + List mediaFields = new ArrayList(); + for (int j=0; jTitle:

- *

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); - } - } -} - +/* + * 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.entity.adapter.EntityAdapterModel; +import mir.entity.adapter.EntityIteratorAdapter; +import mir.log.LoggerWrapper; +import mir.servlet.ServletModule; +import mir.servlet.ServletModuleExc; +import mir.servlet.ServletModuleFailure; +import mir.servlet.ServletModuleUserExc; +import mir.util.CachingRewindableIterator; +import mir.util.HTTPRequestParser; +import mir.util.URLBuilder; +import mircoders.entity.EntityUsers; +import mircoders.global.MirGlobal; +import mircoders.module.ModuleUsers; +import mircoders.storage.DatabaseUsers; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.*; + +/** + * + * + */ +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 { + definition = "user"; + usersModule = new ModuleUsers(); + 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); + + logAdminUsage(aRequest, id, "object added"); + + if (requestParser.hasParameter("returnurl")) + ServletHelper.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); + String id = requestParser.getParameter("id"); + EntityUsers user = (EntityUsers) mainModule.getById(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"); + if (!withValues.containsKey("is_disabled")) + withValues.put("is_disabled","0"); + + String newPassword=validatePassword(ServletHelper.getUser(aRequest), requestParser); + if (newPassword!=null) + withValues.put("password", MirGlobal.localizer().adminInterface().makePasswordDigest(newPassword)); + + mainModule.set(withValues); + + logAdminUsage(aRequest, id, "object modified"); + + if (requestParser.hasParameter("returnurl")) + ServletHelper.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); + String id = requestParser.getParameter("id"); + EntityUsers user = (EntityUsers) mainModule.getById(id); + MirGlobal.accessControl().user().assertMayChangeUserPassword(ServletHelper.getUser(aRequest), user); + + String newPassword=validatePassword(ServletHelper.getUser(aRequest), requestParser); + if (newPassword!=null) { + user.setFieldValue("password", MirGlobal.localizer().adminInterface().makePasswordDigest(newPassword)); + user.update(); + + logAdminUsage(aRequest, id, "password changed"); + + // 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")) + ServletHelper.redirect(aResponse, requestParser.getParameter("returnurl")); + else + ServletHelper.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 + URLBuilder urlBuilder = new URLBuilder(); + int count; + + try { + Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}); + model = MirGlobal.localizer().dataModel().adapterModel(); + + Object userList = + new CachingRewindableIterator( + new EntityIteratorAdapter( "", "login", nrEntitiesPerListPage, + MirGlobal.localizer().dataModel().adapterModel(), "user", nrEntitiesPerListPage, anOffset) + ); + + 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 2499be32..5344273b 100755 --- a/source/mircoders/servlet/ServletModuleVideo.java +++ b/source/mircoders/servlet/ServletModuleVideo.java @@ -32,10 +32,8 @@ package mircoders.servlet; import mir.log.LoggerWrapper; import mir.servlet.ServletModule; -import mir.storage.StorageObjectFailure; import mircoders.module.ModuleUploadedMedia; import mircoders.storage.DatabaseVideo; -import mircoders.global.*; /** * @@ -61,7 +59,6 @@ public class ServletModuleVideo extends ServletModuleUploadedMedia { moduleName = "Video"; try { - model = MirGlobal.localizer().dataModel().adapterModel(); definition = "video"; mainModule = new ModuleUploadedMedia(DatabaseVideo.getInstance()); } diff --git a/source/mircoders/storage/DatabaseArticleType.java b/source/mircoders/storage/DatabaseArticleType.java index d6ed1826..20ea23db 100755 --- a/source/mircoders/storage/DatabaseArticleType.java +++ b/source/mircoders/storage/DatabaseArticleType.java @@ -39,17 +39,14 @@ package mircoders.storage; * @version 1.0 */ -import java.util.List; - -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; public class DatabaseArticleType extends Database implements StorageObject{ private static DatabaseArticleType instance; - private static List articletypePopupData; public synchronized static DatabaseArticleType getInstance() throws StorageObjectFailure { if (instance == null) { @@ -60,9 +57,10 @@ public class DatabaseArticleType extends Database implements StorageObject{ private DatabaseArticleType() throws StorageObjectFailure { super(); + logger = new LoggerWrapper("Database.ArticleType"); this.hasTimestamp = false; - this.theTable = "article_type"; + this.mainTable = "article_type"; } } diff --git a/source/mircoders/storage/DatabaseAudio.java b/source/mircoders/storage/DatabaseAudio.java index 24d6b069..c8c316a2 100755 --- a/source/mircoders/storage/DatabaseAudio.java +++ b/source/mircoders/storage/DatabaseAudio.java @@ -1,84 +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; - -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); - } - -} +/* + * 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; + mainTable = "audio"; + primaryKeySequence = "media_id_seq"; + theEntityClass = mircoders.entity.EntityAudio.class; + } + + public void update(Entity theEntity) throws StorageObjectFailure { + String date = theEntity.getFieldValue("date"); + if (date == null) { + date = StringUtil.date2webdbDate(new GregorianCalendar()); + theEntity.setFieldValue("date", date); + } + + super.update(theEntity); + } + + public String insert(Entity theEntity) throws StorageObjectFailure { + String date = theEntity.getFieldValue("date"); + if (date == null) { + date = StringUtil.date2webdbDate(new GregorianCalendar()); + theEntity.setFieldValue("date", date); + } + return super.insert(theEntity); + } + +} diff --git a/source/mircoders/storage/DatabaseBreaking.java b/source/mircoders/storage/DatabaseBreaking.java index f7c0c87e..a0a68499 100755 --- a/source/mircoders/storage/DatabaseBreaking.java +++ b/source/mircoders/storage/DatabaseBreaking.java @@ -59,7 +59,7 @@ public class DatabaseBreaking extends Database implements StorageObject{ { super(); logger = new LoggerWrapper("Database.Breaking"); - this.theTable="breaking"; + this.mainTable="breaking"; } diff --git a/source/mircoders/storage/DatabaseComment.java b/source/mircoders/storage/DatabaseComment.java index 56f3e336..400b3fa5 100755 --- a/source/mircoders/storage/DatabaseComment.java +++ b/source/mircoders/storage/DatabaseComment.java @@ -30,13 +30,13 @@ 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; /** @@ -60,7 +60,7 @@ public class DatabaseComment extends Database implements StorageObject{ private DatabaseComment() { super(); hasTimestamp = false; - theTable = "comment"; + mainTable = "comment"; logger = new LoggerWrapper("Database.Comment"); this.theEntityClass = mircoders.entity.EntityComment.class; @@ -70,16 +70,15 @@ public class DatabaseComment extends Database implements StorageObject{ Statement stmt = null; Connection con = null; String sql; - int res = 0; - /** @todo comments and topics should be deleted */ - sql = "delete from " + theTable + " where to_media=" + id; + /** todo comments and topics should be deleted */ + sql = "delete from " + mainTable + " where to_media=" + id; logger.info("DELETE "+ sql); try { - con = getPooledCon(); + con = obtainConnection(); stmt = con.createStatement(); - res = stmt.executeUpdate(sql); + stmt.executeUpdate(sql); } catch (SQLException sqe) { new StorageObjectFailure(sqe); diff --git a/source/mircoders/storage/DatabaseCommentStatus.java b/source/mircoders/storage/DatabaseCommentStatus.java index 7cd02d85..40c39375 100755 --- a/source/mircoders/storage/DatabaseCommentStatus.java +++ b/source/mircoders/storage/DatabaseCommentStatus.java @@ -39,9 +39,9 @@ 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; @@ -60,7 +60,7 @@ public class DatabaseCommentStatus extends Database implements StorageObject{ private DatabaseCommentStatus() throws StorageObjectFailure { super(); hasTimestamp = false; - theTable = "comment_status"; + mainTable = "comment_status"; logger = new LoggerWrapper("Database.CommentStatus"); } } \ No newline at end of file diff --git a/source/mircoders/storage/DatabaseCommentToMedia.java b/source/mircoders/storage/DatabaseCommentToMedia.java index 1767ef76..bc7fdf09 100755 --- a/source/mircoders/storage/DatabaseCommentToMedia.java +++ b/source/mircoders/storage/DatabaseCommentToMedia.java @@ -30,24 +30,25 @@ 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 java.util.Vector; + +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.4 2003/09/03 18:29:05 zapata Exp $ + * @version $Id: DatabaseCommentToMedia.java,v 1.5 2004/11/06 20:10:37 idfx Exp $ * */ @@ -64,11 +65,9 @@ public class DatabaseCommentToMedia extends Database implements StorageObject{ private DatabaseCommentToMedia() { super(); - logger = new LoggerWrapper("Database.CommentToMedia"); - hasTimestamp = false; - theTable = "comment_x_media"; + mainTable = "comment_x_media"; theEntityClass = mir.entity.GenericEntity.class; } @@ -76,11 +75,7 @@ public class DatabaseCommentToMedia extends Database implements StorageObject{ StorageObjectExc { if (comment != null) { try { - if (selectByWhereClause("comment_id=" + comment.getId(), -1).size() == - 0) - return false; - else - return true; + return (getSize("comment_id=" + comment.getId()) == 0) ? false:true; } catch (Exception e) { logger.error("DatabaseCommentToMedia.hasMedia: " + e.toString()); @@ -95,33 +90,35 @@ public class DatabaseCommentToMedia extends Database implements StorageObject{ } } + private EntityList getMultiMediaForComment(StorageObject store, EntityComment comment) + throws StorageObjectFailure { + + EntityList returnList = null; + if (comment != null) { + String id = comment.getId(); + try { + Vector extraTable = new Vector(); + extraTable.add(mainTable+" cxm"); + // 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" + store.selectByWhereClause("m", extraTable, + "m.id=cxm.media_id and cxm.comment_id="+id, "id", -1, -1); + + } catch (Exception e) { + logger.error("DatabaseCommenttToMedia.getMultiMediaForComment: " + e.toString()); + throw new StorageObjectFailure("DatabaseContentToMedia.etMultiMediaForComment: " + + e.toString(), e); + } + } + return returnList; + } + /** * get all the audio belonging to a comment entity - * */ public EntityList getAudio(EntityComment comment) throws StorageObjectFailure { - EntityList returnList = null; - if (comment != null) { - // get all to_topic from media_x_topic - String id = comment.getId(); - //this is not supported by mysql - 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 = DatabaseAudio.getInstance().selectByWhereClause(subselect, - "id", -1); - } - catch (Exception e) { - logger.error("DatabaseCommentToMedia.getAudio: " + e.toString()); - throw new StorageObjectFailure("DatabaseCommentToMedia.getAudio: " + - e.toString(), e); - } - } - return returnList; + return getMultiMediaForComment(DatabaseAudio.getInstance(), comment); } /** @@ -129,118 +126,28 @@ public class DatabaseCommentToMedia extends Database implements StorageObject{ * */ public EntityList getVideo(EntityComment comment) throws StorageObjectFailure { - EntityList returnList = null; - if (comment != null) { - // get all to_topic from media_x_topic - String id = comment.getId(); - //this is not supported by mysql - 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 = DatabaseVideo.getInstance().selectByWhereClause(subselect, - "id", -1); - } - catch (Exception e) { - logger.error("DatabaseCommentToMedia.getVideo: " + e.toString()); - throw new StorageObjectFailure("DatabaseCommentToMedia.getVideo: " + - e.toString(), e); - } - } - return returnList; + return getMultiMediaForComment(DatabaseVideo.getInstance(), comment); } /** * get all the images belonging to a comment entity - * */ - public EntityList getImages(EntityComment comment) throws - StorageObjectFailure { - EntityList returnList = null; - if (comment != null) { - // get all to_topic from media_x_topic - String id = comment.getId(); - //this is not supported by mysql - 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 = DatabaseImages.getInstance().selectByWhereClause(subselect, - "id", -1); - } - catch (Exception e) { - logger.error("DatabaseCommentToMedia.getImages: " + e.toString()); - throw new StorageObjectFailure("DatabaseCommentToMedia.getImages: " + - e.toString(), e); - } - } - return returnList; + public EntityList getImages(EntityComment comment) throws StorageObjectFailure { + return getMultiMediaForComment(DatabaseImages.getInstance(), comment); } /** * get all the uploaded/other Media belonging to a comment entity - * */ public EntityList getOther(EntityComment comment) throws StorageObjectFailure { - /** @todo this should only fetch published media / rk */ - - EntityList returnList = null; - if (comment != null) { - // get all to_topic from media_x_topic - String id = comment.getId(); - //this is not supported by mysql - 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 = DatabaseOther.getInstance().selectByWhereClause(subselect, - "id"); - } - catch (Exception e) { - logger.error("DatabaseCommentToMedia.getOther: " + e.toString()); - throw new StorageObjectFailure("DatabaseCommentToMedia.getOther: " + e.toString(), e); - } - } - return returnList; + return getMultiMediaForComment(DatabaseOther.getInstance(), comment); } /** * get all the uploaded/other Media belonging to a comment entity - * */ - public EntityList getUploadedMedia(EntityComment comment) throws - StorageObjectFailure { - /** @todo this should only fetch published media / rk */ - - EntityList returnList = null; - if (comment != null) { - // get all to_topic from media_x_topic - String id = comment.getId(); - //this is not supported by mysql - String subselect = "id in (select media_id from " + theTable + - " where comment_id=" + id + ")"; - - try { - returnList = DatabaseUploadedMedia.getInstance().selectByWhereClause( - subselect, - "id"); - } - catch (Exception e) { - logger.error("DatabaseCommentToMedia.getUploadedMedia: " + e.toString()); - throw new StorageObjectFailure( - "DatabaseCommentToMedia.getUploadedMedia: " + e.toString(), e); - } - } - return returnList; + public EntityList getUploadedMedia(EntityComment comment) throws StorageObjectFailure { + return getMultiMediaForComment(DatabaseUploadedMedia.getInstance(), comment); } public void setMedia(String commentId, String[] mediaId) throws @@ -252,12 +159,12 @@ public class DatabaseCommentToMedia extends Database implements StorageObject{ return; } //first delete all row with comment_id=commentId - String sql = "delete from " + theTable + " where comment_id=" + commentId; + String sql = "delete from " + mainTable + " where comment_id=" + commentId; Connection con = null; Statement stmt = null; try { - con = getPooledCon(); + con = obtainConnection(); // should be a preparedStatement because is faster stmt = con.createStatement(); ResultSet rs = executeSql(stmt, sql); @@ -273,10 +180,10 @@ public class DatabaseCommentToMedia extends Database implements StorageObject{ //now insert //first delete all row with comment_id=commentId for (int i = 0; i < mediaId.length; i++) { - sql = "insert into " + theTable + " (comment_id,media_id) values (" + sql = "insert into " + mainTable + " (comment_id,media_id) values (" + commentId + "," + mediaId[i] + ")"; try { - con = getPooledCon(); + con = obtainConnection(); // should be a preparedStatement because is faster stmt = con.createStatement(); int rs = executeUpdate(stmt, sql); @@ -301,10 +208,10 @@ public class DatabaseCommentToMedia extends Database implements StorageObject{ Statement stmt = null; //now insert - String sql = "insert into " + theTable + " (comment_id,media_id) values (" + String sql = "insert into " + mainTable + " (comment_id,media_id) values (" + commentId + "," + mediaId + ")"; try { - con = getPooledCon(); + con = obtainConnection(); // should be a preparedStatement because is faster stmt = con.createStatement(); int rs = executeUpdate(stmt, sql); @@ -324,12 +231,12 @@ public class DatabaseCommentToMedia extends Database implements StorageObject{ return; } //first delete all row with comment_id=commentId - String sql = "delete from " + theTable + " where comment_id=" + commentId; + String sql = "delete from " + mainTable + " where comment_id=" + commentId; Connection con = null; Statement stmt = null; try { - con = getPooledCon(); + con = obtainConnection(); // should be a preparedStatement because is faster stmt = con.createStatement(); int rs = executeUpdate(stmt, sql); @@ -345,10 +252,10 @@ public class DatabaseCommentToMedia extends Database implements StorageObject{ //now insert //first delete all row with comment_id=commentId - sql = "insert into " + theTable + " (comment_id,media_id) values (" + sql = "insert into " + mainTable + " (comment_id,media_id) values (" + commentId + "," + mediaId + ")"; try { - con = getPooledCon(); + con = obtainConnection(); // should be a preparedStatement because is faster stmt = con.createStatement(); int rs = executeUpdate(stmt, sql); @@ -368,12 +275,12 @@ public class DatabaseCommentToMedia extends Database implements StorageObject{ return; } //delete all row with comment_id=commentId - String sql = "delete from " + theTable + " where comment_id=" + commentId; + String sql = "delete from " + mainTable + " where comment_id=" + commentId; Connection con = null; Statement stmt = null; try { - con = getPooledCon(); + con = obtainConnection(); // should be a preparedStatement because is faster stmt = con.createStatement(); int rs = executeUpdate(stmt, sql); @@ -394,12 +301,12 @@ public class DatabaseCommentToMedia extends Database implements StorageObject{ return; } //delete all row with comment_id=commentId - String sql = "delete from " + theTable + " where media_id=" + mediaId; + String sql = "delete from " + mainTable + " where media_id=" + mediaId; Connection con = null; Statement stmt = null; try { - con = getPooledCon(); + con = obtainConnection(); // should be a preparedStatement because is faster stmt = con.createStatement(); int rs = executeUpdate(stmt, sql); @@ -421,13 +328,13 @@ public class DatabaseCommentToMedia extends Database implements StorageObject{ return; } //delete all row with comment_id=commentId and media_id=mediaId - String sql = "delete from " + theTable + " where media_id=" + mediaId + + String sql = "delete from " + mainTable + " where media_id=" + mediaId + " and comment_id= " + commentId; Connection con = null; Statement stmt = null; try { - con = getPooledCon(); + con = obtainConnection(); // should be a preparedStatement because is faster stmt = con.createStatement(); int rs = executeUpdate(stmt, sql); @@ -444,86 +351,51 @@ public class DatabaseCommentToMedia extends Database implements StorageObject{ public EntityList getComment(EntityUploadedMedia media) throws StorageObjectFailure { + EntityList returnList = null; if (media != null) { + String id = media.getId(); - String select = "select comment_id from " + theTable + " where media_id=" + - id; + Vector extraTables = new Vector(); + extraTables.add(mainTable + " cxm"); - // execute select statement - Connection con = null; - Statement stmt = null; + String mediaSelect = "cxm.comment_id=c.id and cxm.media_id="+id; try { - con = getPooledCon(); - // should be a preparedStatement because is faster - stmt = con.createStatement(); - ResultSet rs = executeSql(stmt, select); - if (rs != null) { - String mediaSelect = "id IN ("; - boolean first = true; - while (rs.next()) { - if (first == false) - mediaSelect += ","; - mediaSelect += rs.getString(1); - first = false; - } - mediaSelect += ")"; - if (first == false) - returnList = DatabaseComment.getInstance().selectByWhereClause( - mediaSelect, -1); - } + returnList = DatabaseComment.getInstance().selectByWhereClause("c", + extraTables, mediaSelect, "c.id" ); + } catch (Exception e) { logger.error("-- get comment failed"); throw new StorageObjectFailure("-- get comment failed -- ", e); } - finally { - freeConnection(con, stmt); - } } return returnList; } /** - * Returns a EntityList with all comment-objects having a relation to a media + * Returns a EntityList with all comment-objects having + * a relation to a media */ public EntityList getComment() throws StorageObjectFailure { EntityList returnList = null; - String select = "select distinct comment_id from " + theTable; - // execute select statement - Connection con = null; - Statement stmt = null; + Vector extraTables = new Vector(); + extraTables.add(mainTable + " cxm"); + + String mediaSelect = "cxm.comment_id=c.id"; try { - con = getPooledCon(); - // should be a preparedStatement because is faster - stmt = con.createStatement(); - ResultSet rs = executeSql(stmt, select); - if (rs != null) { - String mediaSelect = "id IN ("; - boolean first = true; - while (rs.next()) { - if (first == false) - mediaSelect += ","; - mediaSelect += rs.getString(1); - first = false; - } - mediaSelect += ")"; - if (first == false) - returnList = DatabaseComment.getInstance().selectByWhereClause( - mediaSelect, "webdb_lastchange desc"); - } + returnList = DatabaseComment.getInstance().selectByWhereClause("c", + extraTables, mediaSelect, "c.webdb_lastchange desc" ); + } catch (Exception e) { logger.error("-- get comment failed"); throw new StorageObjectFailure("-- get comment failed -- ", e); } - finally { - freeConnection(con, stmt); - } - return returnList; + } } diff --git a/source/mircoders/storage/DatabaseContent.java b/source/mircoders/storage/DatabaseContent.java index b28c5e0c..53c00f79 100755 --- a/source/mircoders/storage/DatabaseContent.java +++ b/source/mircoders/storage/DatabaseContent.java @@ -30,12 +30,12 @@ package mircoders.storage; -import java.sql.Connection; -import java.sql.Statement; - -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; /** @@ -64,8 +64,8 @@ public class DatabaseContent extends Database implements StorageObject { private DatabaseContent() throws StorageObjectFailure { super(); - theTable="content"; - theCoreTable="media"; + mainTable="content"; + primaryKeySequence="media_id_seq"; logger = new LoggerWrapper("Database.Content"); theEntityClass = mircoders.entity.EntityContent.class; @@ -83,7 +83,7 @@ public class DatabaseContent extends Database implements StorageObject { String sql = "update content set is_produced='0' where " + where; logger.debug("set unproduced: "+where); try { - con = getPooledCon(); + con = obtainConnection(); // should be a preparedStatement because is faster stmt = con.createStatement(); executeUpdate(stmt,sql); diff --git a/source/mircoders/storage/DatabaseContentToMedia.java b/source/mircoders/storage/DatabaseContentToMedia.java index ce7572aa..9c0ada72 100755 --- a/source/mircoders/storage/DatabaseContentToMedia.java +++ b/source/mircoders/storage/DatabaseContentToMedia.java @@ -30,24 +30,25 @@ 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 java.util.Vector; + +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.20 2003/09/03 18:29:05 zapata Exp $ + * @version $Id: DatabaseContentToMedia.java,v 1.21 2004/11/06 20:10:37 idfx Exp $ * */ @@ -66,9 +67,8 @@ public class DatabaseContentToMedia extends Database implements StorageObject{ super(); logger = new LoggerWrapper("Database.ContentToMedia"); - hasTimestamp = false; - theTable = "content_x_media"; + mainTable = "content_x_media"; theEntityClass = mir.entity.GenericEntity.class; } @@ -76,11 +76,7 @@ public class DatabaseContentToMedia extends Database implements StorageObject{ StorageObjectExc { if (content != null) { try { - if (selectByWhereClause("content_id=" + content.getId(), -1).size() == - 0) - return false; - else - return true; + return (getSize("content_id=" + content.getId()) == 0) ? false:true; } catch (Exception e) { logger.error("DatabaseContentToMedia.hasMedia: " + e.toString()); @@ -95,169 +91,77 @@ public class DatabaseContentToMedia extends Database implements StorageObject{ } } - /** - * get all the audio belonging to a content entity - * - */ - public EntityList getAudio(EntityContent content) throws StorageObjectFailure { + private EntityList getMultiMediaForContent(StorageObject store, EntityContent content) + throws StorageObjectFailure { + EntityList returnList = null; if (content != null) { - // get all to_topic from media_x_topic String id = content.getId(); - //this is not supported by mysql - String subselect = "id in (select media_id from " + theTable + - " where content_id=" + id + ")"; - try { + Vector extraTable = new Vector(); + extraTable.add(mainTable+" cxm"); // 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 = DatabaseAudio.getInstance().selectByWhereClause(subselect, - "id", -1); - } - catch (Exception e) { - logger.error("DatabaseContentToMedia.getAudio: " + e.toString()); - throw new StorageObjectFailure("DatabaseContentToMedia.getAudio: " + - e.toString(), e); + store.selectByWhereClause("m", extraTable, + "m.id=cxm.media_id and cxm.content_id="+id, "id", -1, -1); + + } catch (Exception e) { + logger.error("DatabaseContentToMedia.getMultiMediaForContent: " + e.toString()); + throw new StorageObjectFailure("DatabaseContentToMedia.etMultiMediaForContent: " + + e.toString(), e); } } return returnList; } /** + * get all the audio belonging to a content entity + */ + public EntityList getAudio(EntityContent content) throws StorageObjectFailure { + return getMultiMediaForContent(DatabaseAudio.getInstance(), content); + } + + /** * get all the video belonging to a content entity - * */ public EntityList getVideo(EntityContent content) throws StorageObjectFailure { - EntityList returnList = null; - if (content != null) { - // get all to_topic from media_x_topic - String id = content.getId(); - //this is not supported by mysql - 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 = DatabaseVideo.getInstance().selectByWhereClause(subselect, - "id", -1); - } - catch (Exception e) { - logger.error("DatabaseContentToMedia.getVideo: " + e.toString()); - throw new StorageObjectFailure("DatabaseContentToMedia.getVideo: " + - e.toString(), e); - } - } - return returnList; + return getMultiMediaForContent(DatabaseVideo.getInstance(), content); } /** * get all the images belonging to a content entity - * */ - public EntityList getImages(EntityContent content) throws - StorageObjectFailure { - EntityList returnList = null; - if (content != null) { - // get all to_topic from media_x_topic - String id = content.getId(); - //this is not supported by mysql - 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 = DatabaseImages.getInstance().selectByWhereClause(subselect, - "id", -1); - } - catch (Exception e) { - logger.error("DatabaseContentToMedia.getImages: " + e.toString()); - throw new StorageObjectFailure("DatabaseContentToMedia.getImages: " + - e.toString(), e); - } - } - return returnList; + public EntityList getImages(EntityContent content) throws StorageObjectFailure { + return getMultiMediaForContent(DatabaseImages.getInstance(), content); } /** * get all the uploaded/other Media belonging to a content entity - * */ public EntityList getOther(EntityContent content) throws StorageObjectFailure { - /** @todo this should only fetch published media / rk */ - - EntityList returnList = null; - if (content != null) { - // get all to_topic from media_x_topic - String id = content.getId(); - //this is not supported by mysql - 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 = DatabaseOther.getInstance().selectByWhereClause(subselect, - "id"); - } - catch (Exception e) { - logger.error("DatabaseContentToMedia.getOther: " + e.toString()); - throw new StorageObjectFailure("DatabaseContentToMedia.getOther: " + e.toString(), e); - } - } - return returnList; + return getMultiMediaForContent(DatabaseOther.getInstance(), content); } /** * get all the uploaded/other Media belonging to a content entity - * */ - public EntityList getUploadedMedia(EntityContent content) throws - StorageObjectFailure { - /** @todo this should only fetch published media / rk */ - - EntityList returnList = null; - if (content != null) { - // get all to_topic from media_x_topic - String id = content.getId(); - //this is not supported by mysql - String subselect = "id in (select media_id from " + theTable + - " where content_id=" + id + ")"; - - try { - returnList = DatabaseUploadedMedia.getInstance().selectByWhereClause( - subselect, - "id"); - } - catch (Exception e) { - logger.error("DatabaseContentToMedia.getUploadedMedia: " + e.toString()); - throw new StorageObjectFailure( - "DatabaseContentToMedia.getUploadedMedia: " + e.toString(), e); - } - } - return returnList; + public EntityList getUploadedMedia(EntityContent content) throws StorageObjectFailure { + return getMultiMediaForContent(DatabaseUploadedMedia.getInstance(), content); } - public void setMedia(String contentId, String[] mediaId) throws - StorageObjectFailure { - if (contentId == null) { - return; - } - if (mediaId == null || mediaId[0] == null) { + + public void setMedia(String contentId, String[] mediaId) throws StorageObjectFailure { + if (contentId == null || mediaId == null || mediaId[0] == null) { return; } //first delete all row with content_id=contentId - String sql = "delete from " + theTable + " where content_id=" + contentId; + String sql = "delete from " + mainTable + " where content_id=" + contentId; Connection con = null; Statement stmt = null; try { - con = getPooledCon(); + con = obtainConnection(); // should be a preparedStatement because is faster stmt = con.createStatement(); ResultSet rs = executeSql(stmt, sql); @@ -273,10 +177,10 @@ public class DatabaseContentToMedia extends Database implements StorageObject{ //now insert //first delete all row with content_id=contentId for (int i = 0; i < mediaId.length; i++) { - sql = "insert into " + theTable + " (content_id,media_id) values (" + sql = "insert into " + mainTable + " (content_id,media_id) values (" + contentId + "," + mediaId[i] + ")"; try { - con = getPooledCon(); + con = obtainConnection(); // should be a preparedStatement because is faster stmt = con.createStatement(); int rs = executeUpdate(stmt, sql); @@ -301,10 +205,10 @@ public class DatabaseContentToMedia extends Database implements StorageObject{ Statement stmt = null; //now insert - String sql = "insert into " + theTable + " (content_id,media_id) values (" + String sql = "insert into " + mainTable + " (content_id,media_id) values (" + contentId + "," + mediaId + ")"; try { - con = getPooledCon(); + con = obtainConnection(); // should be a preparedStatement because is faster stmt = con.createStatement(); int rs = executeUpdate(stmt, sql); @@ -324,12 +228,12 @@ public class DatabaseContentToMedia extends Database implements StorageObject{ return; } //first delete all row with content_id=contentId - String sql = "delete from " + theTable + " where content_id=" + contentId; + String sql = "delete from " + mainTable + " where content_id=" + contentId; Connection con = null; Statement stmt = null; try { - con = getPooledCon(); + con = obtainConnection(); // should be a preparedStatement because is faster stmt = con.createStatement(); int rs = executeUpdate(stmt, sql); @@ -345,10 +249,10 @@ public class DatabaseContentToMedia extends Database implements StorageObject{ //now insert //first delete all row with content_id=contentId - sql = "insert into " + theTable + " (content_id,media_id) values (" + sql = "insert into " + mainTable + " (content_id,media_id) values (" + contentId + "," + mediaId + ")"; try { - con = getPooledCon(); + con = obtainConnection(); // should be a preparedStatement because is faster stmt = con.createStatement(); int rs = executeUpdate(stmt, sql); @@ -368,12 +272,12 @@ public class DatabaseContentToMedia extends Database implements StorageObject{ return; } //delete all row with content_id=contentId - String sql = "delete from " + theTable + " where content_id=" + contentId; + String sql = "delete from " + mainTable + " where content_id=" + contentId; Connection con = null; Statement stmt = null; try { - con = getPooledCon(); + con = obtainConnection(); // should be a preparedStatement because is faster stmt = con.createStatement(); int rs = executeUpdate(stmt, sql); @@ -389,17 +293,18 @@ public class DatabaseContentToMedia extends Database implements StorageObject{ } public void deleteByMediaId(String mediaId) throws StorageObjectFailure { + if (mediaId == null) { //theLog.printDebugInfo("-- delete topics failed -- no topic id"); return; } //delete all row with content_id=contentId - String sql = "delete from " + theTable + " where media_id=" + mediaId; + String sql = "delete from " + mainTable + " where media_id=" + mediaId; Connection con = null; Statement stmt = null; try { - con = getPooledCon(); + con = obtainConnection(); // should be a preparedStatement because is faster stmt = con.createStatement(); int rs = executeUpdate(stmt, sql); @@ -421,13 +326,13 @@ public class DatabaseContentToMedia extends Database implements StorageObject{ return; } //delete all row with content_id=contentId and media_id=mediaId - String sql = "delete from " + theTable + " where media_id=" + mediaId + + String sql = "delete from " + mainTable + " where media_id=" + mediaId + " and content_id= " + contentId; Connection con = null; Statement stmt = null; try { - con = getPooledCon(); + con = obtainConnection(); // should be a preparedStatement because is faster stmt = con.createStatement(); int rs = executeUpdate(stmt, sql); @@ -444,42 +349,24 @@ public class DatabaseContentToMedia extends Database implements StorageObject{ public EntityList getContent(EntityUploadedMedia media) throws StorageObjectFailure { + EntityList returnList = null; if (media != null) { + String id = media.getId(); - String select = "select content_id from " + theTable + " where media_id=" + - id; + Vector extraTables = new Vector(); + extraTables.add(mainTable + " cxm"); - // execute select statement - Connection con = null; - Statement stmt = null; + String mediaSelect = "cxm.content_id=c.id and cxm.media_id="+id; try { - con = getPooledCon(); - // should be a preparedStatement because is faster - stmt = con.createStatement(); - ResultSet rs = executeSql(stmt, select); - if (rs != null) { - String mediaSelect = "id IN ("; - boolean first = true; - while (rs.next()) { - if (first == false) - mediaSelect += ","; - mediaSelect += rs.getString(1); - first = false; - } - mediaSelect += ")"; - if (first == false) - returnList = DatabaseContent.getInstance().selectByWhereClause( - mediaSelect, -1); - } + returnList = DatabaseContent.getInstance().selectByWhereClause("c", + extraTables, mediaSelect, "c.id" ); + } catch (Exception e) { logger.error("-- get content failed"); throw new StorageObjectFailure("-- get content failed -- ", e); } - finally { - freeConnection(con, stmt); - } } return returnList; } @@ -489,40 +376,22 @@ public class DatabaseContentToMedia extends Database implements StorageObject{ */ public EntityList getContent() throws StorageObjectFailure { + EntityList returnList = null; - String select = "select distinct content_id from " + theTable; - // execute select statement - Connection con = null; - Statement stmt = null; + Vector extraTables = new Vector(); + extraTables.add(mainTable + " cxm"); + + String mediaSelect = "cxm.content_id=c.id"; try { - con = getPooledCon(); - // should be a preparedStatement because is faster - stmt = con.createStatement(); - ResultSet rs = executeSql(stmt, select); - if (rs != null) { - String mediaSelect = "id IN ("; - boolean first = true; - while (rs.next()) { - if (first == false) - mediaSelect += ","; - mediaSelect += rs.getString(1); - first = false; - } - mediaSelect += ")"; - if (first == false) - returnList = DatabaseContent.getInstance().selectByWhereClause( - mediaSelect, "webdb_lastchange desc"); - } + returnList = DatabaseContent.getInstance().selectByWhereClause("c", + extraTables, mediaSelect, "c.webdb_lastchange desc" ); + } catch (Exception e) { logger.error("-- get content failed"); throw new StorageObjectFailure("-- get content failed -- ", e); } - finally { - freeConnection(con, stmt); - } - return returnList; } diff --git a/source/mircoders/storage/DatabaseContentToTopics.java b/source/mircoders/storage/DatabaseContentToTopics.java index 4a696e41..2186c5ef 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; /** @@ -70,24 +70,24 @@ public class DatabaseContentToTopics extends Database implements StorageObject{ logger = new LoggerWrapper("Database.ContentToTopics"); hasTimestamp = false; - theTable="content_x_topic"; + mainTable="content_x_topic"; theEntityClass = mir.entity.GenericEntity.class; } /** * This class return an EntityList of Topics - * @param EntityContent content - * @returns EntityList */ public EntityList getTopics(EntityContent content) { EntityList returnList=null; if (content != null) { - // get all to_topic from content_x_topic - String id = content.getId(); - String subselect = "id in (select topic_id from " + theTable + " where content_id=" + id+")"; + String id = content.getId(); try { - returnList = DatabaseTopics.getInstance().selectByWhereClause(subselect,-1); + Vector extraTables = new Vector(); + extraTables.add(mainTable+" cxt"); + returnList = DatabaseTopics.getInstance() + .selectByWhereClauseWithExtraTables("t",extraTables, + "t.id=cxt.topic_id and cxt.content_id="+id ); } catch (Exception e) { logger.error("-- get topics failed " + e.toString()); @@ -97,24 +97,24 @@ public class DatabaseContentToTopics extends Database implements StorageObject{ } /** - * Returns a ArrayList of Integer-Objects from a content-id. - * @returns ArrayList + * Returns a List of String-Objects from a content-id. */ public List getTopicsOfContent(String contentId) throws StorageObjectFailure { ArrayList returnList = new ArrayList(); if (contentId != null) { - String sql = "select topic_id from " + theTable + " where content_id=" + contentId; + String sql = "select topic_id from " + mainTable + " where content_id=" + contentId; Connection con=null;Statement stmt=null; try { - con = getPooledCon(); + con = obtainConnection(); + // should be a preparedStatement because is faster stmt = con.createStatement(); ResultSet rs = executeSql(stmt,sql); if(rs!=null){ while(rs.next()){ - returnList.add(new Integer(rs.getInt("topic_id"))); + returnList.add(Integer.toString(rs.getInt("topic_id"))); } } } @@ -161,9 +161,9 @@ public class DatabaseContentToTopics extends Database implements StorageObject{ List currentTopics = getTopicsOfContent(anArticleId); logger.debug("New topics = " + newTopics.toString()); logger.debug("Current topics = " + currentTopics.toString()); - List topicsToDelete = new Vector(currentTopics); + List topicsToDelete = new ArrayList(currentTopics); topicsToDelete.removeAll(newTopics); - List topicsToAdd = new Vector(newTopics); + List topicsToAdd = new ArrayList(newTopics); topicsToAdd.removeAll(currentTopics); logger.debug("to delete = " + topicsToDelete.toString()); logger.debug("to add = " + topicsToAdd.toString()); @@ -171,16 +171,16 @@ public class DatabaseContentToTopics extends Database implements StorageObject{ if (!topicsToDelete.isEmpty()) { String sql = - "delete from " + theTable + " " + + "delete from " + mainTable + " " + "where content_id=" + anArticleId + " and topic_id in (" + getIdListExpression(topicsToDelete) + ")"; Connection connection=null; Statement statement=null; try { - connection = getPooledCon(); + connection = obtainConnection(); statement = connection.createStatement(); - int rs = executeUpdate(statement, sql); + executeUpdate(statement, sql); } catch (Exception e) { logger.error("-- deleting topics failed"); @@ -198,15 +198,15 @@ public class DatabaseContentToTopics extends Database implements StorageObject{ while (i.hasNext()) { Integer topicId = (Integer) i.next(); String sql = - "insert into " + theTable + " (content_id, topic_id) "+ + "insert into " + mainTable + " (content_id, topic_id) "+ "values (" + anArticleId + "," + topicId + ")"; Connection connection=null; Statement statement=null; try { - connection = getPooledCon(); + connection = obtainConnection(); // should be a preparedStatement because is faster statement = connection.createStatement(); - int rs = executeUpdate(statement, sql); + executeUpdate(statement, sql); } catch (Exception e) { logger.error("-- adding topics failed"); @@ -228,14 +228,14 @@ public class DatabaseContentToTopics extends Database implements StorageObject{ return; } //delete all row with content_id=contentId - String sql = "delete from "+ theTable +" where content_id=" + contentId; + String sql = "delete from "+ mainTable +" where content_id=" + contentId; Connection con=null;Statement stmt=null; try { - con = getPooledCon(); + con = obtainConnection(); // should be a preparedStatement because is faster stmt = con.createStatement(); - ResultSet rs = executeSql(stmt,sql); + executeSql(stmt,sql); } catch (Exception e) { //theLog.printDebugInfo("-- delete topics failed "); } finally { @@ -250,14 +250,14 @@ public class DatabaseContentToTopics extends Database implements StorageObject{ return; } //delete all row with content_id=contentId - String sql = "delete from "+ theTable +" where topic_id=" + topicId; + String sql = "delete from "+ mainTable +" where topic_id=" + topicId; Connection con=null;Statement stmt=null; try { - con = getPooledCon(); + con = obtainConnection(); // should be a preparedStatement because is faster stmt = con.createStatement(); - ResultSet rs = executeSql(stmt,sql); + executeSql(stmt,sql); } catch (Exception e) { logger.error("-- delete topics failed "); @@ -267,38 +267,27 @@ public class DatabaseContentToTopics extends Database implements StorageObject{ } } - +/** + * Returns list of Content for a specific topic + * @param topic + * @return EntityList + * @throws StorageObjectFailure + */ public EntityList getContent(EntityTopics topic) throws StorageObjectFailure { EntityList returnList=null; if (topic != null) { String id = topic.getId(); - String select = "select content_id from " + theTable + " where topic_id=" + id; - - // execute select statement - Connection con=null;Statement stmt=null; try { - con = getPooledCon(); - // should be a preparedStatement because is faster - stmt = con.createStatement(); - ResultSet rs = executeSql(stmt,select); - if (rs!=null) { - String topicSelect= "id IN ("; - boolean first=true; - while (rs.next()) { - if (first==false) topicSelect+=","; - topicSelect += rs.getString(1); - first=false; - } - topicSelect+=")"; - if (first==false) - returnList = DatabaseContent.getInstance().selectByWhereClause(topicSelect,-1); - } + Vector extraTables = new Vector(); + extraTables.add(mainTable+" cxt"); + returnList = DatabaseContent.getInstance() + .selectByWhereClauseWithExtraTables("c",extraTables, + "c.id=cxt.content_id and cxt.topic_id="+id ); } catch (Exception e) { - logger.error("-- get contetn failed"); + logger.error("-- get content failed"); } - finally { freeConnection(con,stmt);} } return returnList; } diff --git a/source/mircoders/storage/DatabaseImageColor.java b/source/mircoders/storage/DatabaseImageColor.java index bbf37db6..6881eba5 100755 --- a/source/mircoders/storage/DatabaseImageColor.java +++ b/source/mircoders/storage/DatabaseImageColor.java @@ -30,8 +30,8 @@ package mircoders.storage; -import mir.log.LoggerWrapper; -import mir.storage.Database; +import mir.log.LoggerWrapper; +import mir.storage.Database; import mir.storage.StorageObject; /** @@ -58,7 +58,7 @@ public class DatabaseImageColor extends Database implements StorageObject{ super(); logger = new LoggerWrapper("Database.ImageColor"); hasTimestamp = false; - theTable = "img_color"; + mainTable = "img_color"; } } diff --git a/source/mircoders/storage/DatabaseImageFormat.java b/source/mircoders/storage/DatabaseImageFormat.java index 26f2a8d8..210dfb21 100755 --- a/source/mircoders/storage/DatabaseImageFormat.java +++ b/source/mircoders/storage/DatabaseImageFormat.java @@ -30,8 +30,8 @@ package mircoders.storage; -import mir.log.LoggerWrapper; -import mir.storage.Database; +import mir.log.LoggerWrapper; +import mir.storage.Database; import mir.storage.StorageObject; /** @@ -58,6 +58,6 @@ public class DatabaseImageFormat extends Database implements StorageObject{ super(); logger = new LoggerWrapper("Database.ImageFormat"); hasTimestamp = false; - theTable = "img_format"; + mainTable = "img_format"; } } diff --git a/source/mircoders/storage/DatabaseImageLayout.java b/source/mircoders/storage/DatabaseImageLayout.java index 641f9035..8e48eb30 100755 --- a/source/mircoders/storage/DatabaseImageLayout.java +++ b/source/mircoders/storage/DatabaseImageLayout.java @@ -30,8 +30,8 @@ package mircoders.storage; -import mir.log.LoggerWrapper; -import mir.storage.Database; +import mir.log.LoggerWrapper; +import mir.storage.Database; import mir.storage.StorageObject; /** @@ -59,6 +59,6 @@ public class DatabaseImageLayout extends Database implements StorageObject{ logger = new LoggerWrapper("Database.ImageLayout"); hasTimestamp = false; - theTable = "img_layout"; + mainTable = "img_layout"; } } diff --git a/source/mircoders/storage/DatabaseImageType.java b/source/mircoders/storage/DatabaseImageType.java index a924eb59..8bf91f4e 100755 --- a/source/mircoders/storage/DatabaseImageType.java +++ b/source/mircoders/storage/DatabaseImageType.java @@ -1,63 +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; - -/** - * - *

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"; - } -} +/* + * 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; + mainTable = "img_type"; + } +} diff --git a/source/mircoders/storage/DatabaseImages.java b/source/mircoders/storage/DatabaseImages.java index 681fbaa9..33a07699 100755 --- a/source/mircoders/storage/DatabaseImages.java +++ b/source/mircoders/storage/DatabaseImages.java @@ -1,91 +1,90 @@ -/* - * 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); - } -} +/* + * 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; + +/** + * 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; + mainTable = "images"; + primaryKeySequence = "media_id_seq"; + theEntityClass = mircoders.entity.EntityImages.class; + } + + public void update(Entity theEntity) throws StorageObjectFailure { + String date = theEntity.getFieldValue("date"); + if (date == null) { + date = StringUtil.date2webdbDate(new GregorianCalendar()); + theEntity.setFieldValue("date", date); + } + + super.update(theEntity); + } + + public String insert(Entity theEntity) throws StorageObjectFailure { + String date = theEntity.getFieldValue("date"); + + if (date == null) { + date = StringUtil.date2webdbDate(new GregorianCalendar()); + theEntity.setFieldValue("date", date); + } + + return super.insert(theEntity); + } +} diff --git a/source/mircoders/storage/DatabaseLanguage.java b/source/mircoders/storage/DatabaseLanguage.java index a1ed74da..61f9958a 100755 --- a/source/mircoders/storage/DatabaseLanguage.java +++ b/source/mircoders/storage/DatabaseLanguage.java @@ -1,93 +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 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; - } -} +/* + * 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.mainTable = "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.getFieldValue("name")); + + result.add(entry); + } + + return result; + } +} diff --git a/source/mircoders/storage/DatabaseMediaType.java b/source/mircoders/storage/DatabaseMediaType.java index cd2cf1a1..fd900f95 100755 --- a/source/mircoders/storage/DatabaseMediaType.java +++ b/source/mircoders/storage/DatabaseMediaType.java @@ -58,7 +58,7 @@ public class DatabaseMediaType extends Database implements StorageObject{ logger = new LoggerWrapper("Database.MediaType"); hasTimestamp = false; - theTable="media_type"; + mainTable="media_type"; theEntityClass = mir.entity.GenericEntity.class; } diff --git a/source/mircoders/storage/DatabaseMediafolder.java b/source/mircoders/storage/DatabaseMediafolder.java index aaccbe4c..a9d3dd4b 100755 --- a/source/mircoders/storage/DatabaseMediafolder.java +++ b/source/mircoders/storage/DatabaseMediafolder.java @@ -1,59 +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; - -/** - * - */ - -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"; - } -} +/* + * 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; + mainTable="media_folder"; + } +} diff --git a/source/mircoders/storage/DatabaseMessages.java b/source/mircoders/storage/DatabaseMessages.java index 81ad6968..efac2e7f 100755 --- a/source/mircoders/storage/DatabaseMessages.java +++ b/source/mircoders/storage/DatabaseMessages.java @@ -61,7 +61,7 @@ public class DatabaseMessages extends Database implements StorageObject{ logger = new LoggerWrapper("Database.Messages"); - this.theTable="messages"; + this.mainTable="messages"; } diff --git a/source/mircoders/storage/DatabaseOther.java b/source/mircoders/storage/DatabaseOther.java index 712f542f..c4c422be 100755 --- a/source/mircoders/storage/DatabaseOther.java +++ b/source/mircoders/storage/DatabaseOther.java @@ -1,97 +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; - -/** - * - *

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 - -} +/* + * 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; + mainTable = "other_media"; + primaryKeySequence = "media_id_seq"; + theEntityClass = mircoders.entity.EntityOther.class; + } + + public void update(Entity theEntity) throws StorageObjectFailure { + String date = theEntity.getFieldValue("date"); + if (date == null) { + date = StringUtil.date2webdbDate(new GregorianCalendar()); + theEntity.setFieldValue("date", date); + } + + super.update(theEntity); + } + + public String insert(Entity theEntity) throws StorageObjectFailure { + String date = theEntity.getFieldValue("date"); + if (date == null) { + date = StringUtil.date2webdbDate(new GregorianCalendar()); + theEntity.setFieldValue("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 5bdbd087..d2a5c632 100755 --- a/source/mircoders/storage/DatabaseRights.java +++ b/source/mircoders/storage/DatabaseRights.java @@ -61,6 +61,6 @@ public class DatabaseRights extends Database implements StorageObject{ logger = new LoggerWrapper("Database.Rights"); hasTimestamp = false; - theTable = "rights"; + mainTable = "rights"; } } diff --git a/source/mircoders/storage/DatabaseTopics.java b/source/mircoders/storage/DatabaseTopics.java index 95f5df8b..252ae0b3 100755 --- a/source/mircoders/storage/DatabaseTopics.java +++ b/source/mircoders/storage/DatabaseTopics.java @@ -1,91 +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.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; - } -} +/* + * 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; + mainTable = "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.getFieldValue("title")); + + result.add(entry); + } + + return result; + } +} diff --git a/source/mircoders/storage/DatabaseUploadedMedia.java b/source/mircoders/storage/DatabaseUploadedMedia.java index 8c2000f0..ce42e110 100755 --- a/source/mircoders/storage/DatabaseUploadedMedia.java +++ b/source/mircoders/storage/DatabaseUploadedMedia.java @@ -30,13 +30,13 @@ package mircoders.storage; -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 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 { @@ -55,8 +55,8 @@ public class DatabaseUploadedMedia extends Database implements StorageObject { logger = new LoggerWrapper("Database.UploadedMedia"); - theTable="uploaded_media"; - theCoreTable="media"; + mainTable="uploaded_media"; + primaryKeySequence="media_id_seq"; theEntityClass = mircoders.entity.EntityUploadedMedia.class; } @@ -68,7 +68,7 @@ public class DatabaseUploadedMedia extends Database implements StorageObject { public Entity getMediaType(Entity ent) throws StorageObjectFailure { Entity type=null; try { - Iterator i = new EntityBrowser(DatabaseMediaType.getInstance(), ent.getValue("to_media_type") + " = id" , "id", 1); + Iterator i = new EntityBrowser(DatabaseMediaType.getInstance(), ent.getFieldValue("to_media_type") + " = id" , "id", 1); if (i.hasNext()) type = (Entity) i.next(); } diff --git a/source/mircoders/storage/DatabaseUsers.java b/source/mircoders/storage/DatabaseUsers.java index 29dddacc..3e2c4b32 100755 --- a/source/mircoders/storage/DatabaseUsers.java +++ b/source/mircoders/storage/DatabaseUsers.java @@ -65,7 +65,7 @@ public class DatabaseUsers extends Database implements StorageObject{ logger = new LoggerWrapper("Database.Users"); hasTimestamp = false; - theTable = "webdb_users"; + mainTable = "webdb_users"; theEntityClass = mircoders.entity.EntityUsers.class; } } diff --git a/source/mircoders/storage/DatabaseVideo.java b/source/mircoders/storage/DatabaseVideo.java index 5f2b1382..4595bef9 100755 --- a/source/mircoders/storage/DatabaseVideo.java +++ b/source/mircoders/storage/DatabaseVideo.java @@ -30,7 +30,7 @@ package mircoders.storage; -import java.util.*; +import java.util.GregorianCalendar; import mir.entity.Entity; import mir.log.LoggerWrapper; @@ -69,26 +69,26 @@ public class DatabaseVideo extends Database implements StorageObject{ logger = new LoggerWrapper("Database.Video"); hasTimestamp = true; - theTable = "video"; - theCoreTable = "media"; + mainTable = "video"; + primaryKeySequence = "media_id_seq"; theEntityClass = mircoders.entity.EntityVideo.class; } public void update(Entity theEntity) throws StorageObjectFailure { - String date = theEntity.getValue("date"); + String date = theEntity.getFieldValue("date"); if (date == null) { date = StringUtil.date2webdbDate(new GregorianCalendar()); - theEntity.setValueForProperty("date", date); + theEntity.setFieldValue("date", date); } super.update(theEntity); } public String insert(Entity theEntity) throws StorageObjectFailure { - String date = theEntity.getValue("date"); + String date = theEntity.getFieldValue("date"); if (date == null) { date = StringUtil.date2webdbDate(new GregorianCalendar()); - theEntity.setValueForProperty("date", date); + theEntity.setFieldValue("date", date); } return super.insert(theEntity); }