From 77b8f79d3873d20aa10bb775e03047cd6a9de0bf Mon Sep 17 00:00:00 2001 From: idfx Date: Sat, 8 Mar 2003 17:18:18 +0000 Subject: [PATCH] organising imports --- source/Mir.java | 978 +++++----- source/OpenMir.java | 5 +- source/mir/servlet/ServletModule.java | 995 +++++----- source/mir/util/ExceptionFunctions.java | 4 +- source/mircoders/entity/EntityImages.java | 558 +++--- source/mircoders/module/ModuleComment.java | 4 +- .../mircoders/producer/IndexingProducerNode.java | 4 +- .../producer/PDFGeneratingProducerNode.java | 2 +- .../mircoders/producer/UnIndexingProducerNode.java | 4 +- source/mircoders/servlet/ServletHelper.java | 2 +- source/mircoders/servlet/ServletModuleAdmin.java | 2 - .../mircoders/servlet/ServletModuleBreaking.java | 2 - source/mircoders/servlet/ServletModuleComment.java | 2 - source/mircoders/servlet/ServletModuleContent.java | 1110 ++++++----- .../mircoders/servlet/ServletModuleFileEdit.java | 5 +- source/mircoders/servlet/ServletModuleHidden.java | 3 - .../mircoders/servlet/ServletModuleLinksImcs.java | 3 - source/mircoders/servlet/ServletModuleMessage.java | 2 - .../mircoders/servlet/ServletModuleOpenIndy.java | 1965 ++++++++++---------- .../mircoders/servlet/ServletModuleProducer.java | 1 - .../servlet/ServletModuleUploadedMedia.java | 779 ++++---- source/mircoders/servlet/ServletModuleUsers.java | 356 ++-- 22 files changed, 3378 insertions(+), 3408 deletions(-) diff --git a/source/Mir.java b/source/Mir.java index 31650ea7..48c57975 100755 --- a/source/Mir.java +++ b/source/Mir.java @@ -1,489 +1,489 @@ -/* - * 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 the com.oreilly.servlet library, 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.io.PrintWriter; -import java.lang.reflect.Method; -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.ServletException; -import javax.servlet.UnavailableException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import mir.config.MirPropertiesConfiguration; -import mir.generator.FreemarkerGenerator; -import mir.log.LoggerWrapper; -import mir.misc.HTMLTemplateProcessor; -import mir.misc.StringUtil; -import mir.servlet.AbstractServlet; -import mir.servlet.ServletModule; -import mir.servlet.ServletModuleDispatch; -import mir.servlet.ServletModuleExc; -import mir.servlet.ServletModuleUserExc; -import mir.util.StringRoutines; -import mir.util.ExceptionFunctions; -import mircoders.entity.EntityUsers; -import mircoders.global.MirGlobal; -import mircoders.module.ModuleMessage; -import mircoders.module.ModuleUsers; -import mircoders.storage.DatabaseArticleType; -import mircoders.storage.DatabaseMessages; -import mircoders.storage.DatabaseUsers; - -import org.apache.struts.util.MessageResources; - -import freemarker.template.SimpleHash; -import freemarker.template.SimpleList; -import freemarker.template.SimpleScalar; -import freemarker.template.TemplateModel; - - - -/** - * Mir.java - main servlet, that dispatches to servletmodules - * - * @author $Author: zapata $ - * @version $Id: Mir.java,v 1.34 2003/03/07 00:50:22 zapata Exp $ - * - */ -public class Mir extends AbstractServlet { - private static ModuleUsers usersModule = null; - private static ModuleMessage messageModule = null; - private final static Map servletModuleInstanceHash = new HashMap(); - - //I don't know about making this static cause it removes the - //possibility to change the config on the fly.. -mh - private static List loginLanguages = null; - public HttpSession session; - - public void doGet(HttpServletRequest aRequest, HttpServletResponse aResponse) - throws ServletException, IOException { - doPost(aRequest, aResponse); - } - - protected TemplateModel getLoginLanguages() throws ServletException { - synchronized (Mir.class) { - try { - if (loginLanguages == null) { - MessageResources messageResources2 = - MessageResources.getMessageResources("bundles.admin"); - MessageResources messageResources = - MessageResources.getMessageResources("bundles.adminlocal"); - List languages = - StringRoutines.splitString(MirGlobal.getConfigPropertyWithDefault( - "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 FreemarkerGenerator.makeAdapter(loginLanguages); - } - catch (Throwable t) { - throw new ServletException(t.getMessage()); - } - } - } - - // FIXME: this should probalby go into AbstractServlet so it can be used in - // OpenMir as well -mh - protected String getDefaultLanguage(HttpServletRequest aRequest) { - String defaultlanguage = - MirGlobal.getConfigPropertyWithDefault("Mir.Login.DefaultLanguage", ""); - - if (defaultlanguage.length() == 0) { - Locale locale = aRequest.getLocale(); - defaultlanguage = locale.getLanguage(); - } - - return defaultlanguage; - } - - public void doPost(HttpServletRequest aRequest, HttpServletResponse aResponse) - throws ServletException, IOException, UnavailableException { - long startTime = System.currentTimeMillis(); - long sessionConnectTime = 0; - EntityUsers userEntity; - String http = ""; - - if ((configuration.getString("RootUri") == null) || - configuration.getString("RootUri").equals("")) { - configuration.setProperty("RootUri", aRequest.getContextPath()); - } - - configuration.addProperty("ServletName", getServletName()); - - //*** test - // Log.info(this, "blalalala"); - session = aRequest.getSession(true); - userEntity = (EntityUsers) session.getAttribute("login.uid"); - - if (aRequest.getServerPort() == 443) { - http = "https"; - } else { - http = "http"; - } - - //make sure client browsers don't cache anything - setNoCaching(aResponse); - - //FIXME: this seems kind of hackish and only here because we can have - // default other than the one that the browser is set to. - Locale locale = new Locale(getDefaultLanguage(aRequest), ""); - MessageResources messageResources = - MessageResources.getMessageResources("bundles.admin"); - String htmlcharset = messageResources.getMessage(locale, "htmlcharset"); - - aResponse.setContentType("text/html; charset=" + htmlcharset); - - String moduleName = aRequest.getParameter("module"); - checkLanguage(session, aRequest); - - /** @todo for cleanup and readability this should be moved to - * method loginIfNecessary() */ - if ((moduleName != null) && moduleName.equals("direct")) { - //... - } - - // Authentication - if (((moduleName != null) && moduleName.equals("login")) || - (userEntity == null)) { - String user = aRequest.getParameter("login"); - String passwd = aRequest.getParameter("password"); - logger.debug("--login: evaluating for user: " + user); - userEntity = allowedUser(user, passwd); - - if (userEntity == null) { - // login failed: redirecting to login - logger.warn("--login: failed!"); - _sendLoginPage(aResponse, aRequest, aResponse.getWriter()); - - return; - } else if ((moduleName != null) && moduleName.equals("login")) { - // login successful - logger.info("--login: successful! setting uid: " + userEntity.getId()); - session.setAttribute("login.uid", userEntity); - logger.debug("--login: trying to retrieve login.target"); - - String target = (String) session.getAttribute("login.target"); - - if (target != null) { - logger.debug("Redirect: " + target); - - int serverPort = aRequest.getServerPort(); - String redirect = ""; - String redirectString = ""; - - if (serverPort == 80) { - redirect = - aResponse.encodeURL(http + "://" + aRequest.getServerName() + target); - redirectString = - "going Mir"; - } else { - redirect = - aResponse.encodeURL(http + "://" + aRequest.getServerName() + ":" + - aRequest.getServerPort() + target); - redirectString = - "going Mir"; - } - - aResponse.getWriter().println(redirectString); - - //aResponse.sendRedirect(redirect); - } else { - // redirecting to default target - logger.debug("--login: no target - redirecting to default"); - _sendStartPage(aResponse, aRequest, aResponse.getWriter(), userEntity); - } - - return; - } - // if login succesful - } - // if login - - if ((moduleName != null) && moduleName.equals("logout")) { - logger.info("--logout"); - session.invalidate(); - - //session = aRequest.getSession(true); - //checkLanguage(session, aRequest); - _sendLoginPage(aResponse, aRequest, aResponse.getWriter()); - - return; - } - - // Check if authed! - if (userEntity == null) { - // redirect to loginpage - String redirectString = aRequest.getRequestURI(); - String queryString = aRequest.getQueryString(); - - if ((queryString != null) && !queryString.equals("")) { - redirectString += ("?" + aRequest.getQueryString()); - logger.debug("STORING: " + redirectString); - session.setAttribute("login.target", redirectString); - } - - _sendLoginPage(aResponse, aRequest, aResponse.getWriter()); - - return; - } - - // If no module is specified goto standard startpage - if ((moduleName == null) || moduleName.equals("")) { - logger.debug("no module: redirect to standardpage"); - _sendStartPage(aResponse, aRequest, aResponse.getWriter(), userEntity); - - return; - } - - // end of auth - // From now on regular dispatching... - try { - // get servletmodule by parameter and continue with dispacher - ServletModule smod = getServletModuleForName(moduleName); - ServletModuleDispatch.dispatch(smod, aRequest, aResponse); - } - catch (Throwable e) { - Throwable cause = ExceptionFunctions.traceCauseException(e); - - if (cause instanceof ServletModuleUserExc) - handleUserError(aRequest, aResponse, aResponse.getWriter(), (ServletModuleUserExc) cause); - else - handleError(aRequest, aResponse, aResponse.getWriter(), cause); - - } - - // timing... - sessionConnectTime = System.currentTimeMillis() - startTime; - logger.info("EXECTIME (" + moduleName + "): " + sessionConnectTime + " ms"); - } - - /** - * Private method getServletModuleForName returns ServletModule - * from Cache - * - * @param moduleName - * @return ServletModule - * - */ - 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, - PrintWriter out, Throwable anException) { - try { - logger.info("user error: " + anException.getMessage()); - SimpleHash modelRoot = new SimpleHash(); - modelRoot.put("errorstring", new SimpleScalar(anException.getMessage())); - modelRoot.put("date", new SimpleScalar(StringUtil.date2readableDateTime(new GregorianCalendar()))); - HTMLTemplateProcessor.process(aResponse,MirPropertiesConfiguration.instance().getString("Mir.UserErrorTemplate"), - modelRoot, out, aRequest.getLocale() ); - out.close(); - } - catch (Exception e) { - logger.error("Error in UserErrorTemplate"); - } - - } - - private void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse,PrintWriter out, Throwable anException) { - - try { - logger.error("error: " + anException); - SimpleHash modelRoot = new SimpleHash(); - modelRoot.put("errorstring", new SimpleScalar(anException.getMessage())); - modelRoot.put("date", new SimpleScalar(StringUtil.date2readableDateTime( - new GregorianCalendar()))); - HTMLTemplateProcessor.process(aResponse,MirPropertiesConfiguration.instance().getString("Mir.ErrorTemplate"), - modelRoot,out, aRequest.getLocale()); - out.close(); - } - catch (Exception e) { - logger.error("Error in ErrorTemplate"); - } - } - - /** - * evaluate login for user / password - */ - protected EntityUsers allowedUser(String user, String password) { - try { - if (usersModule == null) { - usersModule = new ModuleUsers(DatabaseUsers.getInstance()); - } - - return usersModule.getUserForLogin(user, password); - } catch (Exception e) { - logger.debug(e.getMessage()); - e.printStackTrace(); - - return null; - } - } - - // Redirect-methods - private void _sendLoginPage(HttpServletResponse aResponse, HttpServletRequest aRequest, - PrintWriter out) { - String loginTemplate = configuration.getString("Mir.LoginTemplate"); - String sessionUrl = aResponse.encodeURL(""); - - try { - SimpleHash mergeData = new SimpleHash(); - SimpleList languages = new SimpleList(); - - mergeData.put("session", sessionUrl); - - mergeData.put("defaultlanguage", getDefaultLanguage(aRequest)); - mergeData.put("languages", getLoginLanguages()); - - HTMLTemplateProcessor.process(aResponse, loginTemplate, mergeData, out, - getLocale(aRequest)); - } - catch (Throwable e) { - handleError(aRequest, aResponse, out, e); - } - } - - private void _sendStartPage(HttpServletResponse aResponse, HttpServletRequest aRequest, - PrintWriter out, EntityUsers userEntity) { - String startTemplate = "templates/admin/start_admin.template"; - String sessionUrl = aResponse.encodeURL(""); - - try { - // merge with logged in user and messages - SimpleHash mergeData = new SimpleHash(); - mergeData.put("session", sessionUrl); - mergeData.put("login_user", userEntity); - - if (messageModule == null) { - messageModule = new ModuleMessage(DatabaseMessages.getInstance()); - } - - mergeData.put("messages", - messageModule.getByWhereClause(null, "webdb_create desc", 0, 10)); - - mergeData.put("articletypes", - DatabaseArticleType.getInstance().selectByWhereClause("", "id", 0, 20)); - - HTMLTemplateProcessor.process(aResponse, startTemplate, mergeData, out, - getLocale(aRequest)); - } - catch (Exception e) { - e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); - handleError(aRequest, aResponse, out, e); - } - } - - public String getServletInfo() { - return "Mir " + configuration.getString("Mir.Version"); - } - - private void checkLanguage(HttpSession session, HttpServletRequest aRequest) { - // a lang parameter always sets the language - String lang = aRequest.getParameter("language"); - - if (lang != null) { - logger.info("selected language " + lang + " overrides accept-language"); - setLanguage(session, lang); - setLocale(session, new Locale(lang, "")); - } - // otherwise store language from accept header in session - else if (session.getAttribute("Language") == null) { - logger.info("accept-language is " + aRequest.getLocale().getLanguage()); - setLanguage(session, aRequest.getLocale().getLanguage()); - setLocale(session, aRequest.getLocale()); - } - } -} +/* + * 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 the com.oreilly.servlet library, 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.io.PrintWriter; +import java.lang.reflect.Method; +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.ServletException; +import javax.servlet.UnavailableException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import mir.config.MirPropertiesConfiguration; +import mir.generator.FreemarkerGenerator; +import mir.log.LoggerWrapper; +import mir.misc.HTMLTemplateProcessor; +import mir.misc.StringUtil; +import mir.servlet.AbstractServlet; +import mir.servlet.ServletModule; +import mir.servlet.ServletModuleDispatch; +import mir.servlet.ServletModuleExc; +import mir.servlet.ServletModuleUserExc; +import mir.util.ExceptionFunctions; +import mir.util.StringRoutines; +import mircoders.entity.EntityUsers; +import mircoders.global.MirGlobal; +import mircoders.module.ModuleMessage; +import mircoders.module.ModuleUsers; +import mircoders.storage.DatabaseArticleType; +import mircoders.storage.DatabaseMessages; +import mircoders.storage.DatabaseUsers; + +import org.apache.struts.util.MessageResources; + +import freemarker.template.SimpleHash; +import freemarker.template.SimpleList; +import freemarker.template.SimpleScalar; +import freemarker.template.TemplateModel; + + + +/** + * Mir.java - main servlet, that dispatches to servletmodules + * + * @author $Author: idfx $ + * @version $Id: Mir.java,v 1.35 2003/03/08 17:18:19 idfx Exp $ + * + */ +public class Mir extends AbstractServlet { + private static ModuleUsers usersModule = null; + private static ModuleMessage messageModule = null; + private final static Map servletModuleInstanceHash = new HashMap(); + + //I don't know about making this static cause it removes the + //possibility to change the config on the fly.. -mh + private static List loginLanguages = null; + public HttpSession session; + + public void doGet(HttpServletRequest aRequest, HttpServletResponse aResponse) + throws ServletException, IOException { + doPost(aRequest, aResponse); + } + + protected TemplateModel getLoginLanguages() throws ServletException { + synchronized (Mir.class) { + try { + if (loginLanguages == null) { + MessageResources messageResources2 = + MessageResources.getMessageResources("bundles.admin"); + MessageResources messageResources = + MessageResources.getMessageResources("bundles.adminlocal"); + List languages = + StringRoutines.splitString(MirGlobal.getConfigPropertyWithDefault( + "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 FreemarkerGenerator.makeAdapter(loginLanguages); + } + catch (Throwable t) { + throw new ServletException(t.getMessage()); + } + } + } + + // FIXME: this should probalby go into AbstractServlet so it can be used in + // OpenMir as well -mh + protected String getDefaultLanguage(HttpServletRequest aRequest) { + String defaultlanguage = + MirGlobal.getConfigPropertyWithDefault("Mir.Login.DefaultLanguage", ""); + + if (defaultlanguage.length() == 0) { + Locale locale = aRequest.getLocale(); + defaultlanguage = locale.getLanguage(); + } + + return defaultlanguage; + } + + public void doPost(HttpServletRequest aRequest, HttpServletResponse aResponse) + throws ServletException, IOException, UnavailableException { + long startTime = System.currentTimeMillis(); + long sessionConnectTime = 0; + EntityUsers userEntity; + String http = ""; + + if ((configuration.getString("RootUri") == null) || + configuration.getString("RootUri").equals("")) { + configuration.setProperty("RootUri", aRequest.getContextPath()); + } + + configuration.addProperty("ServletName", getServletName()); + + //*** test + // Log.info(this, "blalalala"); + session = aRequest.getSession(true); + userEntity = (EntityUsers) session.getAttribute("login.uid"); + + if (aRequest.getServerPort() == 443) { + http = "https"; + } else { + http = "http"; + } + + //make sure client browsers don't cache anything + setNoCaching(aResponse); + + //FIXME: this seems kind of hackish and only here because we can have + // default other than the one that the browser is set to. + Locale locale = new Locale(getDefaultLanguage(aRequest), ""); + MessageResources messageResources = + MessageResources.getMessageResources("bundles.admin"); + String htmlcharset = messageResources.getMessage(locale, "htmlcharset"); + + aResponse.setContentType("text/html; charset=" + htmlcharset); + + String moduleName = aRequest.getParameter("module"); + checkLanguage(session, aRequest); + + /** @todo for cleanup and readability this should be moved to + * method loginIfNecessary() */ + if ((moduleName != null) && moduleName.equals("direct")) { + //... + } + + // Authentication + if (((moduleName != null) && moduleName.equals("login")) || + (userEntity == null)) { + String user = aRequest.getParameter("login"); + String passwd = aRequest.getParameter("password"); + logger.debug("--login: evaluating for user: " + user); + userEntity = allowedUser(user, passwd); + + if (userEntity == null) { + // login failed: redirecting to login + logger.warn("--login: failed!"); + _sendLoginPage(aResponse, aRequest, aResponse.getWriter()); + + return; + } else if ((moduleName != null) && moduleName.equals("login")) { + // login successful + logger.info("--login: successful! setting uid: " + userEntity.getId()); + session.setAttribute("login.uid", userEntity); + logger.debug("--login: trying to retrieve login.target"); + + String target = (String) session.getAttribute("login.target"); + + if (target != null) { + logger.debug("Redirect: " + target); + + int serverPort = aRequest.getServerPort(); + String redirect = ""; + String redirectString = ""; + + if (serverPort == 80) { + redirect = + aResponse.encodeURL(http + "://" + aRequest.getServerName() + target); + redirectString = + "going Mir"; + } else { + redirect = + aResponse.encodeURL(http + "://" + aRequest.getServerName() + ":" + + aRequest.getServerPort() + target); + redirectString = + "going Mir"; + } + + aResponse.getWriter().println(redirectString); + + //aResponse.sendRedirect(redirect); + } else { + // redirecting to default target + logger.debug("--login: no target - redirecting to default"); + _sendStartPage(aResponse, aRequest, aResponse.getWriter(), userEntity); + } + + return; + } + // if login succesful + } + // if login + + if ((moduleName != null) && moduleName.equals("logout")) { + logger.info("--logout"); + session.invalidate(); + + //session = aRequest.getSession(true); + //checkLanguage(session, aRequest); + _sendLoginPage(aResponse, aRequest, aResponse.getWriter()); + + return; + } + + // Check if authed! + if (userEntity == null) { + // redirect to loginpage + String redirectString = aRequest.getRequestURI(); + String queryString = aRequest.getQueryString(); + + if ((queryString != null) && !queryString.equals("")) { + redirectString += ("?" + aRequest.getQueryString()); + logger.debug("STORING: " + redirectString); + session.setAttribute("login.target", redirectString); + } + + _sendLoginPage(aResponse, aRequest, aResponse.getWriter()); + + return; + } + + // If no module is specified goto standard startpage + if ((moduleName == null) || moduleName.equals("")) { + logger.debug("no module: redirect to standardpage"); + _sendStartPage(aResponse, aRequest, aResponse.getWriter(), userEntity); + + return; + } + + // end of auth + // From now on regular dispatching... + try { + // get servletmodule by parameter and continue with dispacher + ServletModule smod = getServletModuleForName(moduleName); + ServletModuleDispatch.dispatch(smod, aRequest, aResponse); + } + catch (Throwable e) { + Throwable cause = ExceptionFunctions.traceCauseException(e); + + if (cause instanceof ServletModuleUserExc) + handleUserError(aRequest, aResponse, aResponse.getWriter(), (ServletModuleUserExc) cause); + else + handleError(aRequest, aResponse, aResponse.getWriter(), cause); + + } + + // timing... + sessionConnectTime = System.currentTimeMillis() - startTime; + logger.info("EXECTIME (" + moduleName + "): " + sessionConnectTime + " ms"); + } + + /** + * Private method getServletModuleForName returns ServletModule + * from Cache + * + * @param moduleName + * @return ServletModule + * + */ + 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, + PrintWriter out, Throwable anException) { + try { + logger.info("user error: " + anException.getMessage()); + SimpleHash modelRoot = new SimpleHash(); + modelRoot.put("errorstring", new SimpleScalar(anException.getMessage())); + modelRoot.put("date", new SimpleScalar(StringUtil.date2readableDateTime(new GregorianCalendar()))); + HTMLTemplateProcessor.process(aResponse,MirPropertiesConfiguration.instance().getString("Mir.UserErrorTemplate"), + modelRoot, out, aRequest.getLocale() ); + out.close(); + } + catch (Exception e) { + logger.error("Error in UserErrorTemplate"); + } + + } + + private void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse,PrintWriter out, Throwable anException) { + + try { + logger.error("error: " + anException); + SimpleHash modelRoot = new SimpleHash(); + modelRoot.put("errorstring", new SimpleScalar(anException.getMessage())); + modelRoot.put("date", new SimpleScalar(StringUtil.date2readableDateTime( + new GregorianCalendar()))); + HTMLTemplateProcessor.process(aResponse,MirPropertiesConfiguration.instance().getString("Mir.ErrorTemplate"), + modelRoot,out, aRequest.getLocale()); + out.close(); + } + catch (Exception e) { + logger.error("Error in ErrorTemplate"); + } + } + + /** + * evaluate login for user / password + */ + protected EntityUsers allowedUser(String user, String password) { + try { + if (usersModule == null) { + usersModule = new ModuleUsers(DatabaseUsers.getInstance()); + } + + return usersModule.getUserForLogin(user, password); + } catch (Exception e) { + logger.debug(e.getMessage()); + e.printStackTrace(); + + return null; + } + } + + // Redirect-methods + private void _sendLoginPage(HttpServletResponse aResponse, HttpServletRequest aRequest, + PrintWriter out) { + String loginTemplate = configuration.getString("Mir.LoginTemplate"); + String sessionUrl = aResponse.encodeURL(""); + + try { + SimpleHash mergeData = new SimpleHash(); + SimpleList languages = new SimpleList(); + + mergeData.put("session", sessionUrl); + + mergeData.put("defaultlanguage", getDefaultLanguage(aRequest)); + mergeData.put("languages", getLoginLanguages()); + + HTMLTemplateProcessor.process(aResponse, loginTemplate, mergeData, out, + getLocale(aRequest)); + } + catch (Throwable e) { + handleError(aRequest, aResponse, out, e); + } + } + + private void _sendStartPage(HttpServletResponse aResponse, HttpServletRequest aRequest, + PrintWriter out, EntityUsers userEntity) { + String startTemplate = "templates/admin/start_admin.template"; + String sessionUrl = aResponse.encodeURL(""); + + try { + // merge with logged in user and messages + SimpleHash mergeData = new SimpleHash(); + mergeData.put("session", sessionUrl); + mergeData.put("login_user", userEntity); + + if (messageModule == null) { + messageModule = new ModuleMessage(DatabaseMessages.getInstance()); + } + + mergeData.put("messages", + messageModule.getByWhereClause(null, "webdb_create desc", 0, 10)); + + mergeData.put("articletypes", + DatabaseArticleType.getInstance().selectByWhereClause("", "id", 0, 20)); + + HTMLTemplateProcessor.process(aResponse, startTemplate, mergeData, out, + getLocale(aRequest)); + } + catch (Exception e) { + e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); + handleError(aRequest, aResponse, out, e); + } + } + + public String getServletInfo() { + return "Mir " + configuration.getString("Mir.Version"); + } + + private void checkLanguage(HttpSession session, HttpServletRequest aRequest) { + // a lang parameter always sets the language + String lang = aRequest.getParameter("language"); + + if (lang != null) { + logger.info("selected language " + lang + " overrides accept-language"); + setLanguage(session, lang); + setLocale(session, new Locale(lang, "")); + } + // otherwise store language from accept header in session + else if (session.getAttribute("Language") == null) { + logger.info("accept-language is " + aRequest.getLocale().getLanguage()); + setLanguage(session, aRequest.getLocale().getLanguage()); + setLocale(session, aRequest.getLocale()); + } + } +} diff --git a/source/OpenMir.java b/source/OpenMir.java index 3a0a5fad..7b54da24 100755 --- a/source/OpenMir.java +++ b/source/OpenMir.java @@ -44,11 +44,8 @@ import mir.misc.HTMLTemplateProcessor; import mir.misc.StringUtil; import mir.servlet.AbstractServlet; import mir.servlet.ServletModuleDispatch; -import mir.servlet.ServletModuleExc; import mir.servlet.ServletModuleUserExc; -import mir.servlet.ServletModuleFailure; import mir.util.ExceptionFunctions; - import mircoders.servlet.ServletModuleOpenIndy; import freemarker.template.SimpleHash; import freemarker.template.SimpleScalar; @@ -57,7 +54,7 @@ import freemarker.template.SimpleScalar; * 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.23 2003/03/07 00:50:22 zapata Exp $ + * @version $Id: OpenMir.java,v 1.24 2003/03/08 17:18:19 idfx Exp $ * */ diff --git a/source/mir/servlet/ServletModule.java b/source/mir/servlet/ServletModule.java index 76bb1512..a9dfd625 100755 --- a/source/mir/servlet/ServletModule.java +++ b/source/mir/servlet/ServletModule.java @@ -1,499 +1,496 @@ -/* - * 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 the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mir.servlet; - -import java.io.IOException; -import java.io.PrintWriter; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import mir.config.MirPropertiesConfiguration; -import mir.config.MirPropertiesConfiguration.PropertiesConfigExc; -import mir.entity.EntityList; -import mir.log.LoggerWrapper; -import mir.misc.HTMLParseException; -import mir.misc.HTMLTemplateProcessor; -import mir.misc.LineFilterWriter; -import mir.module.AbstractModule; -import mir.module.ModuleException; -import mir.storage.StorageObject; -import mir.util.HTTPRequestParser; -import freemarker.template.SimpleHash; -import freemarker.template.TemplateModelRoot; - - - - -/** - * Abstract class ServletModule provides the base functionality for servlets. - * Deriving a class from ServletModule enables class to insert/edit/update/delete - * and list Entity from a Database via mainModule. - * - * - * Abstrakte Klasse ServletModule stellt die Basisfunktionalitaet der - * abgeleiteten ServletModule zur Verf?gung. - * - * @version 28.6.1999 - * @author RK - */ - -public abstract class ServletModule { - - public String defaultAction; - protected LoggerWrapper logger; - protected MirPropertiesConfiguration configuration; - protected AbstractModule mainModule; - protected String templateListString; - protected String templateObjektString; - protected String templateConfirmString; - - - public ServletModule(){ - try { - configuration = MirPropertiesConfiguration.instance(); - } - catch (PropertiesConfigExc e) { - throw new RuntimeException("Can't get configuration: " + e.getMessage()); - } - } - - - /** - * Singelton - Methode muss in den abgeleiteten Klassen ueberschrieben werden. - * @return ServletModule - */ - public static ServletModule getInstance() { - return null; - } - - /** - * get the module name to be used for generic operations like delete. - */ - protected String getOperationModuleName() { - return getClass().getName().substring((new String("mircoders.servlet.ServletModule")).length()); - } - - /** - * get the session binded language - */ - public String getLanguage(HttpServletRequest req) { - HttpSession session = req.getSession(false); - String language = (String) session.getAttribute("Language"); - if (language == null) { - language = configuration.getString("StandardLanguage"); - } - return language; - } - - /** - * get the locale either from the session or the accept-language header ot the request - * this supersedes getLanguage for the new i18n - */ - public Locale getLocale(HttpServletRequest req) { - Locale loc = null; - HttpSession session = req.getSession(false); - if (session != null) { - // session can be null in case of logout - loc = (Locale) session.getAttribute("Locale"); - } - // if there is nothing in the session get it fron the accept-language - if (loc == null) { - loc = req.getLocale(); - } - return loc; - } - - public void redirect(HttpServletResponse aResponse, String aQuery) throws ServletModuleExc, ServletModuleFailure { - try { - aResponse.sendRedirect(MirPropertiesConfiguration.instance().getString("RootUri") + "/Mir?"+aQuery); - } - catch (Throwable t) { - throw new ServletModuleFailure("ServletModule.redirect: " +t.getMessage(), t); - } - } - - /** - * list(req,res) - generische Listmethode. Wennn die Funktionalitaet - * nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse - * ueberschreiben werden. - * - * @param req Http-Request, das vom Dispatcher durchgereicht wird - * @param res Http-Response, die vom Dispatcher durchgereicht wird - */ - public void list(HttpServletRequest req, HttpServletResponse res) - throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { - try { - EntityList theList; - String offsetParam = req.getParameter("offset"); - int offset = 0; - PrintWriter out = res.getWriter(); - - // hier offsetcode bearbeiten - if (offsetParam != null && !offsetParam.equals("")) { - offset = Integer.parseInt(offsetParam); - } - if (req.getParameter("next") != null) { - offset = Integer.parseInt(req.getParameter("nextoffset")); - } - else { - if (req.getParameter("prev") != null) { - offset = Integer.parseInt(req.getParameter("prevoffset")); - } - } - theList = mainModule.getByWhereClause(null, offset); - - HTMLTemplateProcessor.process(res, templateListString, theList, out, getLocale(req)); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - /** - * add(req,res) - generische Addmethode. Wennn die Funktionalitaet - * nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse - * ueberschreiben werden. - * @param req Http-Request, das vom Dispatcher durchgereicht wird - * @param res Http-Response, die vom Dispatcher durchgereicht wird - */ - public void add(HttpServletRequest req, HttpServletResponse res) - throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { - - try { - SimpleHash mergeData = new SimpleHash(); - mergeData.put("new", "1"); - deliver(req, res, mergeData, templateObjektString); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - /** - * insert(req,res) - generische Insertmethode, folgt auf add. - * Wennn die Funktionalitaet - * nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse - * ueberschreiben werden. - * - * @param req Http-Request, das vom Dispatcher durchgereicht wird - * @param res Http-Response, die vom Dispatcher durchgereicht wird - */ - public void insert(HttpServletRequest req, HttpServletResponse res) - throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { - try { - Map withValues = getIntersectingValues(req, mainModule.getStorageObject()); - logger.debug("--trying to add..."); - String id = mainModule.add(withValues); - logger.debug("--trying to deliver..." + id); - list(req, res); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - /** - * delete(req,res) - generic delete method. Can be overridden in subclasses. - * - */ - - public void delete(HttpServletRequest req, HttpServletResponse res) - throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { - try { - String idParam = req.getParameter("id"); - - if (idParam == null) - throw new ServletModuleExc("Invalid call to delete: no id supplied"); - - String confirmParam = req.getParameter("confirm"); - String cancelParam = req.getParameter("cancel"); - if (confirmParam == null && cancelParam == null) { - SimpleHash mergeData = new SimpleHash(); - - mergeData.put("module", getOperationModuleName()); - mergeData.put("infoString", getOperationModuleName() + ": " + idParam); - mergeData.put("id", idParam); - mergeData.put("where", req.getParameter("where")); - mergeData.put("order", req.getParameter("order")); - mergeData.put("offset", req.getParameter("offset")); - // this stuff is to be compatible with the other more advanced - // search method used for media and comments - mergeData.put("query_media_folder", req.getParameter("query_media_folder")); - mergeData.put("query_is_published", req.getParameter("query_is_published")); - mergeData.put("query_text", req.getParameter("query_text")); - mergeData.put("query_field", req.getParameter("query_field")); - - deliver(req, res, mergeData, templateConfirmString); - } - else { - if (confirmParam != null && !confirmParam.equals("")) { - //theLog.printInfo("delete confirmed!"); - mainModule.deleteById(idParam); - list(req, res); // back to list - } - else { - if (req.getParameter("where") != null) - list(req, res); - else - edit(req, res); - } - } - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - /** - * edit(req,res) - generische Editmethode. Wennn die Funktionalitaet - * nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse - * ueberschreiben werden. - * - * @param req Http-Request, das vom Dispatcher durchgereicht wird - * @param res Http-Response, die vom Dispatcher durchgereicht wird - */ - public void edit(HttpServletRequest req, HttpServletResponse res) - throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { - edit(req, res, req.getParameter("id")); - } - - /** - * edit(req,res) - generische Editmethode. Wennn die Funktionalitaet - * nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse - * ueberschreiben werden. - * - * @param req Http-Request, das vom Dispatcher durchgereicht wird - * @param res Http-Response, die vom Dispatcher durchgereicht wird - */ - public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse, String anIdentifier) - throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { - try { - deliver(aRequest, aResponse, mainModule.getById(anIdentifier), templateObjektString); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - /** - * update(req,res) - generische Updatemethode. Wennn die Funktionalitaet - * nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse - * ueberschreiben werden. - * - * @param req Http-Request, das vom Dispatcher durchgereicht wird - * @param res Http-Response, die vom Dispatcher durchgereicht wird - */ - - public void update(HttpServletRequest req, HttpServletResponse res) - throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { - try { - String idParam = req.getParameter("id"); - Map withValues = getIntersectingValues(req, mainModule.getStorageObject()); - - String id = mainModule.set(withValues); - String whereParam = req.getParameter("where"); - String orderParam = req.getParameter("order"); - - if ((whereParam != null && !whereParam.equals("")) || (orderParam != null && !orderParam.equals(""))) { - list(req, res); - } - else { - edit(req, res); - } - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - /** - * deliver liefert das Template mit dem Filenamen templateFilename - * an den HttpServletResponse res aus, nachdem es mit den Daten aus - * TemplateModelRoot rtm gemischt wurde - * - * @param res Http-Response, die vom Dispatcher durchgereicht wird - * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den - * Daten, die ins Template gemerged werden sollen. - * @param tmpl Name des Templates - * @exception ServletModuleException - */ - public void deliver(HttpServletRequest req, HttpServletResponse res, TemplateModelRoot rtm, - TemplateModelRoot popups, String templateFilename) throws ServletModuleFailure { - if (rtm == null) - rtm = new SimpleHash(); - - try { - PrintWriter out = res.getWriter(); - HTMLTemplateProcessor.process(res, templateFilename, rtm, popups, out, getLocale(req)); - - // we default to admin bundles here, which is not exactly beautiful... - // but this whole producer stuff is going to be rewritten soon. - // ServletModuleOpenIndy overwrites deliver() to use open bundles - // (br1) - out.close(); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - - /** - * deliver liefert das Template mit dem Filenamen templateFilename - * an den HttpServletResponse res aus, nachdem es mit den Daten aus - * TemplateModelRoot rtm gemischt wurde - * - * @param res Http-Response, die vom Dispatcher durchgereicht wird - * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den - * Daten, die ins Template gemerged werden sollen. - * @param tmpl Name des Templates - * @exception ServletModuleException - */ - public void deliver(HttpServletRequest req, HttpServletResponse res, - TemplateModelRoot rtm, String templateFilename) throws ServletModuleFailure { - deliver(req, res, rtm, null, templateFilename); - } - - /** - * deliver liefert das Template mit dem Filenamen templateFilename - * an den HttpServletResponse res aus, nachdem es mit den Daten aus - * TemplateModelRoot rtm gemischt wurde - * - * @param res Http-Response, die vom Dispatcher durchgereicht wird - * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den - * Daten, die ins Template gemerged werden sollen. - * @param tmpl Name des Templates - * @exception ServletModuleException - */ - public void deliver_compressed(HttpServletRequest req, HttpServletResponse res, - TemplateModelRoot rtm, String templateFilename) - throws ServletModuleFailure { - if (rtm == null) rtm = new SimpleHash(); - try { - PrintWriter out = new LineFilterWriter(res.getWriter()); - //PrintWriter out = res.getWriter(); - HTMLTemplateProcessor.process(res, templateFilename, rtm, out, getLocale(req)); - out.close(); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - /** - * deliver liefert das Template mit dem Filenamen templateFilename - * an den HttpServletResponse res aus, nachdem es mit den Daten aus - * TemplateModelRoot rtm gemischt wurde - * - * @param out ist der OutputStream, in den die gergten Daten geschickt werden sollen. - * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den - * Daten, die ins Template gemerged werden sollen. - * @param tmpl Name des Templates - * @exception ServletModuleException - */ - private void deliver(HttpServletResponse res, HttpServletRequest req, PrintWriter out, - TemplateModelRoot rtm, String templateFilename) - throws ServletModuleFailure { - try { - HTMLTemplateProcessor.process(res, templateFilename, rtm, out, - getLocale(req)); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - /** - * Wenn die abgeleitete Klasse diese Methode ueberschreibt und einen String mit einem - * Methodennamen zurueckliefert, dann wird diese Methode bei fehlender Angabe des - * doParameters ausgefuehrt. - * - * @return Name der Default-Action - */ - public String defaultAction() { - return defaultAction; - } - - /** - * Gets the fields from a httprequest and matches them with the metadata from - * the storage object. Returns the keys that match, with their values. - * - * @return Map with the values - */ - public Map getIntersectingValues(HttpServletRequest req, StorageObject theStorage) - throws ServletModuleExc, ServletModuleFailure { - - try { - HTTPRequestParser parser; - List theFieldList; - - logger.debug("using charset: " + req.getParameter("charset")); - logger.debug("using method: " + req.getParameter("do")); - if (req.getParameter("charset") != null) { - parser = new HTTPRequestParser(req, req.getParameter("charset")); - logger.debug("using charset: " + req.getParameter("charset")); - logger.debug("original charset: " + req.getCharacterEncoding()); - } - else { - parser = new HTTPRequestParser(req); - } - - theFieldList = theStorage.getFields(); - - Map withValues = new HashMap(); - String aField, aValue; - - for (int i = 0; i < theFieldList.size(); i++) { - aField = (String) theFieldList.get(i); - - logger.debug("field " + aField + " = " + parser.getParameter(aField)); - - aValue = parser.getParameter(aField); - if (aValue != null) - withValues.put(aField, aValue); - } - return withValues; - } - catch (Throwable e) { - e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); - - throw new ServletModuleFailure( "ServletModule.getIntersectingValues: " + e.getMessage(), 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 the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mir.servlet; + +import java.io.PrintWriter; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import mir.config.MirPropertiesConfiguration; +import mir.config.MirPropertiesConfiguration.PropertiesConfigExc; +import mir.entity.EntityList; +import mir.log.LoggerWrapper; +import mir.misc.HTMLTemplateProcessor; +import mir.misc.LineFilterWriter; +import mir.module.AbstractModule; +import mir.storage.StorageObject; +import mir.util.HTTPRequestParser; +import freemarker.template.SimpleHash; +import freemarker.template.TemplateModelRoot; + + + + +/** + * Abstract class ServletModule provides the base functionality for servlets. + * Deriving a class from ServletModule enables class to insert/edit/update/delete + * and list Entity from a Database via mainModule. + * + * + * Abstrakte Klasse ServletModule stellt die Basisfunktionalitaet der + * abgeleiteten ServletModule zur Verf?gung. + * + * @version 28.6.1999 + * @author RK + */ + +public abstract class ServletModule { + + public String defaultAction; + protected LoggerWrapper logger; + protected MirPropertiesConfiguration configuration; + protected AbstractModule mainModule; + protected String templateListString; + protected String templateObjektString; + protected String templateConfirmString; + + + public ServletModule(){ + try { + configuration = MirPropertiesConfiguration.instance(); + } + catch (PropertiesConfigExc e) { + throw new RuntimeException("Can't get configuration: " + e.getMessage()); + } + } + + + /** + * Singelton - Methode muss in den abgeleiteten Klassen ueberschrieben werden. + * @return ServletModule + */ + public static ServletModule getInstance() { + return null; + } + + /** + * get the module name to be used for generic operations like delete. + */ + protected String getOperationModuleName() { + return getClass().getName().substring((new String("mircoders.servlet.ServletModule")).length()); + } + + /** + * get the session binded language + */ + public String getLanguage(HttpServletRequest req) { + HttpSession session = req.getSession(false); + String language = (String) session.getAttribute("Language"); + if (language == null) { + language = configuration.getString("StandardLanguage"); + } + return language; + } + + /** + * get the locale either from the session or the accept-language header ot the request + * this supersedes getLanguage for the new i18n + */ + public Locale getLocale(HttpServletRequest req) { + Locale loc = null; + HttpSession session = req.getSession(false); + if (session != null) { + // session can be null in case of logout + loc = (Locale) session.getAttribute("Locale"); + } + // if there is nothing in the session get it fron the accept-language + if (loc == null) { + loc = req.getLocale(); + } + return loc; + } + + public void redirect(HttpServletResponse aResponse, String aQuery) throws ServletModuleExc, ServletModuleFailure { + try { + aResponse.sendRedirect(MirPropertiesConfiguration.instance().getString("RootUri") + "/Mir?"+aQuery); + } + catch (Throwable t) { + throw new ServletModuleFailure("ServletModule.redirect: " +t.getMessage(), t); + } + } + + /** + * list(req,res) - generische Listmethode. Wennn die Funktionalitaet + * nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse + * ueberschreiben werden. + * + * @param req Http-Request, das vom Dispatcher durchgereicht wird + * @param res Http-Response, die vom Dispatcher durchgereicht wird + */ + public void list(HttpServletRequest req, HttpServletResponse res) + throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { + try { + EntityList theList; + String offsetParam = req.getParameter("offset"); + int offset = 0; + PrintWriter out = res.getWriter(); + + // hier offsetcode bearbeiten + if (offsetParam != null && !offsetParam.equals("")) { + offset = Integer.parseInt(offsetParam); + } + if (req.getParameter("next") != null) { + offset = Integer.parseInt(req.getParameter("nextoffset")); + } + else { + if (req.getParameter("prev") != null) { + offset = Integer.parseInt(req.getParameter("prevoffset")); + } + } + theList = mainModule.getByWhereClause(null, offset); + + HTMLTemplateProcessor.process(res, templateListString, theList, out, getLocale(req)); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + /** + * add(req,res) - generische Addmethode. Wennn die Funktionalitaet + * nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse + * ueberschreiben werden. + * @param req Http-Request, das vom Dispatcher durchgereicht wird + * @param res Http-Response, die vom Dispatcher durchgereicht wird + */ + public void add(HttpServletRequest req, HttpServletResponse res) + throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { + + try { + SimpleHash mergeData = new SimpleHash(); + mergeData.put("new", "1"); + deliver(req, res, mergeData, templateObjektString); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + /** + * insert(req,res) - generische Insertmethode, folgt auf add. + * Wennn die Funktionalitaet + * nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse + * ueberschreiben werden. + * + * @param req Http-Request, das vom Dispatcher durchgereicht wird + * @param res Http-Response, die vom Dispatcher durchgereicht wird + */ + public void insert(HttpServletRequest req, HttpServletResponse res) + throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { + try { + Map withValues = getIntersectingValues(req, mainModule.getStorageObject()); + logger.debug("--trying to add..."); + String id = mainModule.add(withValues); + logger.debug("--trying to deliver..." + id); + list(req, res); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + /** + * delete(req,res) - generic delete method. Can be overridden in subclasses. + * + */ + + public void delete(HttpServletRequest req, HttpServletResponse res) + throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { + try { + String idParam = req.getParameter("id"); + + if (idParam == null) + throw new ServletModuleExc("Invalid call to delete: no id supplied"); + + String confirmParam = req.getParameter("confirm"); + String cancelParam = req.getParameter("cancel"); + if (confirmParam == null && cancelParam == null) { + SimpleHash mergeData = new SimpleHash(); + + mergeData.put("module", getOperationModuleName()); + mergeData.put("infoString", getOperationModuleName() + ": " + idParam); + mergeData.put("id", idParam); + mergeData.put("where", req.getParameter("where")); + mergeData.put("order", req.getParameter("order")); + mergeData.put("offset", req.getParameter("offset")); + // this stuff is to be compatible with the other more advanced + // search method used for media and comments + mergeData.put("query_media_folder", req.getParameter("query_media_folder")); + mergeData.put("query_is_published", req.getParameter("query_is_published")); + mergeData.put("query_text", req.getParameter("query_text")); + mergeData.put("query_field", req.getParameter("query_field")); + + deliver(req, res, mergeData, templateConfirmString); + } + else { + if (confirmParam != null && !confirmParam.equals("")) { + //theLog.printInfo("delete confirmed!"); + mainModule.deleteById(idParam); + list(req, res); // back to list + } + else { + if (req.getParameter("where") != null) + list(req, res); + else + edit(req, res); + } + } + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + /** + * edit(req,res) - generische Editmethode. Wennn die Funktionalitaet + * nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse + * ueberschreiben werden. + * + * @param req Http-Request, das vom Dispatcher durchgereicht wird + * @param res Http-Response, die vom Dispatcher durchgereicht wird + */ + public void edit(HttpServletRequest req, HttpServletResponse res) + throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { + edit(req, res, req.getParameter("id")); + } + + /** + * edit(req,res) - generische Editmethode. Wennn die Funktionalitaet + * nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse + * ueberschreiben werden. + * + * @param req Http-Request, das vom Dispatcher durchgereicht wird + * @param res Http-Response, die vom Dispatcher durchgereicht wird + */ + public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse, String anIdentifier) + throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { + try { + deliver(aRequest, aResponse, mainModule.getById(anIdentifier), templateObjektString); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + /** + * update(req,res) - generische Updatemethode. Wennn die Funktionalitaet + * nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse + * ueberschreiben werden. + * + * @param req Http-Request, das vom Dispatcher durchgereicht wird + * @param res Http-Response, die vom Dispatcher durchgereicht wird + */ + + public void update(HttpServletRequest req, HttpServletResponse res) + throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { + try { + String idParam = req.getParameter("id"); + Map withValues = getIntersectingValues(req, mainModule.getStorageObject()); + + String id = mainModule.set(withValues); + String whereParam = req.getParameter("where"); + String orderParam = req.getParameter("order"); + + if ((whereParam != null && !whereParam.equals("")) || (orderParam != null && !orderParam.equals(""))) { + list(req, res); + } + else { + edit(req, res); + } + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + /** + * deliver liefert das Template mit dem Filenamen templateFilename + * an den HttpServletResponse res aus, nachdem es mit den Daten aus + * TemplateModelRoot rtm gemischt wurde + * + * @param res Http-Response, die vom Dispatcher durchgereicht wird + * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den + * Daten, die ins Template gemerged werden sollen. + * @param tmpl Name des Templates + * @exception ServletModuleException + */ + public void deliver(HttpServletRequest req, HttpServletResponse res, TemplateModelRoot rtm, + TemplateModelRoot popups, String templateFilename) throws ServletModuleFailure { + if (rtm == null) + rtm = new SimpleHash(); + + try { + PrintWriter out = res.getWriter(); + HTMLTemplateProcessor.process(res, templateFilename, rtm, popups, out, getLocale(req)); + + // we default to admin bundles here, which is not exactly beautiful... + // but this whole producer stuff is going to be rewritten soon. + // ServletModuleOpenIndy overwrites deliver() to use open bundles + // (br1) + out.close(); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + + /** + * deliver liefert das Template mit dem Filenamen templateFilename + * an den HttpServletResponse res aus, nachdem es mit den Daten aus + * TemplateModelRoot rtm gemischt wurde + * + * @param res Http-Response, die vom Dispatcher durchgereicht wird + * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den + * Daten, die ins Template gemerged werden sollen. + * @param tmpl Name des Templates + * @exception ServletModuleException + */ + public void deliver(HttpServletRequest req, HttpServletResponse res, + TemplateModelRoot rtm, String templateFilename) throws ServletModuleFailure { + deliver(req, res, rtm, null, templateFilename); + } + + /** + * deliver liefert das Template mit dem Filenamen templateFilename + * an den HttpServletResponse res aus, nachdem es mit den Daten aus + * TemplateModelRoot rtm gemischt wurde + * + * @param res Http-Response, die vom Dispatcher durchgereicht wird + * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den + * Daten, die ins Template gemerged werden sollen. + * @param tmpl Name des Templates + * @exception ServletModuleException + */ + public void deliver_compressed(HttpServletRequest req, HttpServletResponse res, + TemplateModelRoot rtm, String templateFilename) + throws ServletModuleFailure { + if (rtm == null) rtm = new SimpleHash(); + try { + PrintWriter out = new LineFilterWriter(res.getWriter()); + //PrintWriter out = res.getWriter(); + HTMLTemplateProcessor.process(res, templateFilename, rtm, out, getLocale(req)); + out.close(); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + /** + * deliver liefert das Template mit dem Filenamen templateFilename + * an den HttpServletResponse res aus, nachdem es mit den Daten aus + * TemplateModelRoot rtm gemischt wurde + * + * @param out ist der OutputStream, in den die gergten Daten geschickt werden sollen. + * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den + * Daten, die ins Template gemerged werden sollen. + * @param tmpl Name des Templates + * @exception ServletModuleException + */ + private void deliver(HttpServletResponse res, HttpServletRequest req, PrintWriter out, + TemplateModelRoot rtm, String templateFilename) + throws ServletModuleFailure { + try { + HTMLTemplateProcessor.process(res, templateFilename, rtm, out, + getLocale(req)); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + /** + * Wenn die abgeleitete Klasse diese Methode ueberschreibt und einen String mit einem + * Methodennamen zurueckliefert, dann wird diese Methode bei fehlender Angabe des + * doParameters ausgefuehrt. + * + * @return Name der Default-Action + */ + public String defaultAction() { + return defaultAction; + } + + /** + * Gets the fields from a httprequest and matches them with the metadata from + * the storage object. Returns the keys that match, with their values. + * + * @return Map with the values + */ + public Map getIntersectingValues(HttpServletRequest req, StorageObject theStorage) + throws ServletModuleExc, ServletModuleFailure { + + try { + HTTPRequestParser parser; + List theFieldList; + + logger.debug("using charset: " + req.getParameter("charset")); + logger.debug("using method: " + req.getParameter("do")); + if (req.getParameter("charset") != null) { + parser = new HTTPRequestParser(req, req.getParameter("charset")); + logger.debug("using charset: " + req.getParameter("charset")); + logger.debug("original charset: " + req.getCharacterEncoding()); + } + else { + parser = new HTTPRequestParser(req); + } + + theFieldList = theStorage.getFields(); + + Map withValues = new HashMap(); + String aField, aValue; + + for (int i = 0; i < theFieldList.size(); i++) { + aField = (String) theFieldList.get(i); + + logger.debug("field " + aField + " = " + parser.getParameter(aField)); + + aValue = parser.getParameter(aField); + if (aValue != null) + withValues.put(aField, aValue); + } + return withValues; + } + catch (Throwable e) { + e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); + + throw new ServletModuleFailure( "ServletModule.getIntersectingValues: " + e.getMessage(), e); + } + } + +} diff --git a/source/mir/util/ExceptionFunctions.java b/source/mir/util/ExceptionFunctions.java index 5c06501d..cd6459fe 100755 --- a/source/mir/util/ExceptionFunctions.java +++ b/source/mir/util/ExceptionFunctions.java @@ -31,9 +31,11 @@ package mir.util; +import java.lang.reflect.InvocationTargetException; + import multex.Failure; + import org.xml.sax.SAXException; -import java.lang.reflect.InvocationTargetException; /** * diff --git a/source/mircoders/entity/EntityImages.java b/source/mircoders/entity/EntityImages.java index 6ab1d15d..ea96e811 100755 --- a/source/mircoders/entity/EntityImages.java +++ b/source/mircoders/entity/EntityImages.java @@ -1,279 +1,279 @@ -/* - * 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 the com.oreilly.servlet library, any library - * licensed under the Apache Software License, The Sun (tm) Java Advanced - * Imaging library (JAI), The Sun JIMI library (or with modified versions of - * the above that use the same license as the above), and distribute linked - * combinations including the two. You must obey the GNU General Public - * License in all respects for all of the code used other than the above - * mentioned libraries. If you modify this file, you may extend this exception - * to your version of the file, but you are not obligated to do so. If you do - * not wish to do so, delete this exception statement from your version. - */ - -package mircoders.entity; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; - -import org.postgresql.largeobject.BlobInputStream; -import org.postgresql.largeobject.LargeObject; -import org.postgresql.largeobject.LargeObjectManager; - -import mir.config.MirPropertiesConfiguration; -import mir.misc.FileUtil; -import mir.misc.WebdbImage; -import mir.log.LoggerWrapper; -import mir.storage.StorageObject; -import mir.storage.StorageObjectFailure; - -/** - * Diese Klasse enth?lt die Daten eines MetaObjekts - * - * @author RK, mh, mir-coders - * @version $Id: EntityImages.java,v 1.18 2003/03/08 05:50:42 zapata Exp $ - */ - - -public class EntityImages extends EntityUploadedMedia -{ - - public EntityImages() - { - super(); - - logger = new LoggerWrapper("Entity.UploadedMedia.Images"); - } - - public EntityImages(StorageObject theStorage) { - this(); - setStorage(theStorage); - } - - // - // methods - - - public InputStream getImage() throws StorageObjectFailure { - logger.debug("EntityImages.getimage started"); - java.sql.Connection con=null; - Statement stmt=null; - BlobInputStream in; - InputStream img_in = null; - try { - con = theStorageObject.getPooledCon(); - con.setAutoCommit(false); - LargeObjectManager lom; - java.sql.Connection jCon; - stmt = con.createStatement(); - ResultSet rs = theStorageObject.executeSql(stmt, - "select image_data from images where id="+getId()); - jCon = ((com.codestudio.sql.PoolManConnectionHandle)con) - .getNativeConnection(); - lom = ((org.postgresql.Connection)jCon).getLargeObjectAPI(); - if(rs!=null) { - if (rs.next()) { - LargeObject lob = lom.open(rs.getInt(1)); - in = (BlobInputStream)lob.getInputStream(); - img_in = new ImageInputStream(in, con, stmt); - } - rs.close(); - } - } - catch (Throwable t) { - logger.error("EntityImages.getImage failed: " + t.toString()); - t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); - - try { - con.setAutoCommit(true); - } - catch (Throwable e) { - logger.error("EntityImages.getImage resetting transaction mode failed: " + e.toString()); - e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); - } - - try { - theStorageObject.freeConnection(con, stmt); - } - catch (Throwable e) { - logger.error("EntityImages.getImage freeing connection failed: " +e.toString()); - } - - throwStorageObjectFailure(t, "EntityImages -- getImage failed: "); - } - return img_in; - } - - public void setImage(InputStream in, String type) - throws StorageObjectFailure { - - if (in != null) { - Connection con = null; - PreparedStatement pstmt = null; - File f = null; - try { - logger.debug("EntityImages.settimage :: making internal representation of image"); - - File tempDir = new File(MirPropertiesConfiguration.instance().getString("TempDir")); - f = File.createTempFile("mir", ".tmp", tempDir); - FileUtil.write(f, in); - WebdbImage webdbImage= new WebdbImage(f, type); - logger.debug("EntityImages.settimage :: made internal representation of image"); - - con = theStorageObject.getPooledCon(); - con.setAutoCommit(false); - logger.debug("EntityImages.settimage :: trying to insert image"); - - // setting values - LargeObjectManager lom; - java.sql.Connection jCon; - jCon = ((com.codestudio.sql.PoolManConnectionHandle)con) - .getNativeConnection(); - - lom = ((org.postgresql.Connection) jCon).getLargeObjectAPI(); - - int oidImage = lom.create(); - int oidIcon = lom.create(); - LargeObject lobImage = lom.open(oidImage); - LargeObject lobIcon = lom.open(oidIcon); - webdbImage.setImage(lobImage.getOutputStream()); - webdbImage.setIcon(lobIcon.getOutputStream()); - lobImage.close(); - lobIcon.close(); - - setValueForProperty("img_height", new Integer(webdbImage.getImageHeight()).toString()); - setValueForProperty("img_width", new Integer(webdbImage.getImageWidth()).toString()); - setValueForProperty("icon_height", new Integer(webdbImage.getIconHeight()).toString()); - setValueForProperty("icon_width", new Integer(webdbImage.getIconWidth()).toString()); - setValueForProperty("image_data", new Integer(oidImage).toString()); - setValueForProperty("icon_data", new Integer(oidIcon).toString()); - update(); - } catch (Exception e) { - throwStorageObjectFailure(e, "settimage :: setImage gescheitert: "); - } finally { - try { - if (con!=null) - con.setAutoCommit(true); - // get rid of the temp. file - f.delete(); - } catch (SQLException e) { - throwStorageObjectFailure(e,"Resetting transaction-mode failed"); - } - if (con!=null) - theStorageObject.freeConnection(con,pstmt); - } - } - } - - /** - * Takes an OutputStream as an argument and reads in the data - * from the DB and writes it to the OutputStream. - * - * It will also take care of closing the OutputStream. - */ - public InputStream getIcon() throws StorageObjectFailure { - Connection con=null; - Statement stmt=null; - BlobInputStream in=null; - ImageInputStream img_in=null; - - try { - con = theStorageObject.getPooledCon(); - con.setAutoCommit(false); - LargeObjectManager lom; - java.sql.Connection jCon; - stmt = con.createStatement(); - ResultSet rs = theStorageObject.executeSql(stmt, "select icon_data from images where id="+getId()); - jCon = ((com.codestudio.sql.PoolManConnectionHandle)con) - .getNativeConnection(); - lom = ((org.postgresql.Connection)jCon).getLargeObjectAPI(); - if(rs!=null) { - if (rs.next()) { - LargeObject lob = lom.open(rs.getInt(1)); - in = (BlobInputStream)lob.getInputStream(); - img_in = new ImageInputStream( in, con ,stmt); - //img_data = rs.getBytes(1); - } - rs.close(); - } - } - catch (Throwable t) { - logger.error("EntityImages.getIcon failed: "+t.toString()); - t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); - - try { - con.setAutoCommit(true); - } - catch (SQLException e) { - logger.error("EntityImages.getIcon resetting transaction mode failed: " + e.toString()); - e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); - } - try { - theStorageObject.freeConnection(con, stmt); - } - catch (Throwable e) { - logger.error("EntityImages -- freeing connection failed: " + e.getMessage()); - } - - throwStorageObjectFailure(t, "EntityImages -- getIcon failed:"); - } - - return img_in; - } - - /** - * a small wrapper class that allows us to store the DB connection resources - * that the BlobInputStream is using and free them upon closing of the stream - */ - private class ImageInputStream extends InputStream { - - InputStream _in; - Connection _con; - Statement _stmt; - - public ImageInputStream(BlobInputStream in, Connection con, - Statement stmt ) { - _in = in; - _con = con; - _stmt = stmt; - } - - public void close () throws IOException { - _in.close(); - try { - _con.setAutoCommit(true); - theStorageObject.freeConnection(_con,_stmt); - } catch (Exception e) { - throw new IOException("close(): "+e.toString()); - } - } - - public int read() throws IOException { - return _in.read(); - } - } -} +/* + * 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 the com.oreilly.servlet library, any library + * licensed under the Apache Software License, The Sun (tm) Java Advanced + * Imaging library (JAI), The Sun JIMI library (or with modified versions of + * the above that use the same license as the above), and distribute linked + * combinations including the two. You must obey the GNU General Public + * License in all respects for all of the code used other than the above + * mentioned libraries. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If you do + * not wish to do so, delete this exception statement from your version. + */ + +package mircoders.entity; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import mir.config.MirPropertiesConfiguration; +import mir.log.LoggerWrapper; +import mir.misc.FileUtil; +import mir.misc.WebdbImage; +import mir.storage.StorageObject; +import mir.storage.StorageObjectFailure; + +import org.postgresql.largeobject.BlobInputStream; +import org.postgresql.largeobject.LargeObject; +import org.postgresql.largeobject.LargeObjectManager; + +/** + * Diese Klasse enth?lt die Daten eines MetaObjekts + * + * @author RK, mh, mir-coders + * @version $Id: EntityImages.java,v 1.19 2003/03/08 17:18:19 idfx Exp $ + */ + + +public class EntityImages extends EntityUploadedMedia +{ + + public EntityImages() + { + super(); + + logger = new LoggerWrapper("Entity.UploadedMedia.Images"); + } + + public EntityImages(StorageObject theStorage) { + this(); + setStorage(theStorage); + } + + // + // methods + + + public InputStream getImage() throws StorageObjectFailure { + logger.debug("EntityImages.getimage started"); + java.sql.Connection con=null; + Statement stmt=null; + BlobInputStream in; + InputStream img_in = null; + try { + con = theStorageObject.getPooledCon(); + con.setAutoCommit(false); + LargeObjectManager lom; + java.sql.Connection jCon; + stmt = con.createStatement(); + ResultSet rs = theStorageObject.executeSql(stmt, + "select image_data from images where id="+getId()); + jCon = ((com.codestudio.sql.PoolManConnectionHandle)con) + .getNativeConnection(); + lom = ((org.postgresql.Connection)jCon).getLargeObjectAPI(); + if(rs!=null) { + if (rs.next()) { + LargeObject lob = lom.open(rs.getInt(1)); + in = (BlobInputStream)lob.getInputStream(); + img_in = new ImageInputStream(in, con, stmt); + } + rs.close(); + } + } + catch (Throwable t) { + logger.error("EntityImages.getImage failed: " + t.toString()); + t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); + + try { + con.setAutoCommit(true); + } + catch (Throwable e) { + logger.error("EntityImages.getImage resetting transaction mode failed: " + e.toString()); + e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); + } + + try { + theStorageObject.freeConnection(con, stmt); + } + catch (Throwable e) { + logger.error("EntityImages.getImage freeing connection failed: " +e.toString()); + } + + throwStorageObjectFailure(t, "EntityImages -- getImage failed: "); + } + return img_in; + } + + public void setImage(InputStream in, String type) + throws StorageObjectFailure { + + if (in != null) { + Connection con = null; + PreparedStatement pstmt = null; + File f = null; + try { + logger.debug("EntityImages.settimage :: making internal representation of image"); + + File tempDir = new File(MirPropertiesConfiguration.instance().getString("TempDir")); + f = File.createTempFile("mir", ".tmp", tempDir); + FileUtil.write(f, in); + WebdbImage webdbImage= new WebdbImage(f, type); + logger.debug("EntityImages.settimage :: made internal representation of image"); + + con = theStorageObject.getPooledCon(); + con.setAutoCommit(false); + logger.debug("EntityImages.settimage :: trying to insert image"); + + // setting values + LargeObjectManager lom; + java.sql.Connection jCon; + jCon = ((com.codestudio.sql.PoolManConnectionHandle)con) + .getNativeConnection(); + + lom = ((org.postgresql.Connection) jCon).getLargeObjectAPI(); + + int oidImage = lom.create(); + int oidIcon = lom.create(); + LargeObject lobImage = lom.open(oidImage); + LargeObject lobIcon = lom.open(oidIcon); + webdbImage.setImage(lobImage.getOutputStream()); + webdbImage.setIcon(lobIcon.getOutputStream()); + lobImage.close(); + lobIcon.close(); + + setValueForProperty("img_height", new Integer(webdbImage.getImageHeight()).toString()); + setValueForProperty("img_width", new Integer(webdbImage.getImageWidth()).toString()); + setValueForProperty("icon_height", new Integer(webdbImage.getIconHeight()).toString()); + setValueForProperty("icon_width", new Integer(webdbImage.getIconWidth()).toString()); + setValueForProperty("image_data", new Integer(oidImage).toString()); + setValueForProperty("icon_data", new Integer(oidIcon).toString()); + update(); + } catch (Exception e) { + throwStorageObjectFailure(e, "settimage :: setImage gescheitert: "); + } finally { + try { + if (con!=null) + con.setAutoCommit(true); + // get rid of the temp. file + f.delete(); + } catch (SQLException e) { + throwStorageObjectFailure(e,"Resetting transaction-mode failed"); + } + if (con!=null) + theStorageObject.freeConnection(con,pstmt); + } + } + } + + /** + * Takes an OutputStream as an argument and reads in the data + * from the DB and writes it to the OutputStream. + * + * It will also take care of closing the OutputStream. + */ + public InputStream getIcon() throws StorageObjectFailure { + Connection con=null; + Statement stmt=null; + BlobInputStream in=null; + ImageInputStream img_in=null; + + try { + con = theStorageObject.getPooledCon(); + con.setAutoCommit(false); + LargeObjectManager lom; + java.sql.Connection jCon; + stmt = con.createStatement(); + ResultSet rs = theStorageObject.executeSql(stmt, "select icon_data from images where id="+getId()); + jCon = ((com.codestudio.sql.PoolManConnectionHandle)con) + .getNativeConnection(); + lom = ((org.postgresql.Connection)jCon).getLargeObjectAPI(); + if(rs!=null) { + if (rs.next()) { + LargeObject lob = lom.open(rs.getInt(1)); + in = (BlobInputStream)lob.getInputStream(); + img_in = new ImageInputStream( in, con ,stmt); + //img_data = rs.getBytes(1); + } + rs.close(); + } + } + catch (Throwable t) { + logger.error("EntityImages.getIcon failed: "+t.toString()); + t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); + + try { + con.setAutoCommit(true); + } + catch (SQLException e) { + logger.error("EntityImages.getIcon resetting transaction mode failed: " + e.toString()); + e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); + } + try { + theStorageObject.freeConnection(con, stmt); + } + catch (Throwable e) { + logger.error("EntityImages -- freeing connection failed: " + e.getMessage()); + } + + throwStorageObjectFailure(t, "EntityImages -- getIcon failed:"); + } + + return img_in; + } + + /** + * a small wrapper class that allows us to store the DB connection resources + * that the BlobInputStream is using and free them upon closing of the stream + */ + private class ImageInputStream extends InputStream { + + InputStream _in; + Connection _con; + Statement _stmt; + + public ImageInputStream(BlobInputStream in, Connection con, + Statement stmt ) { + _in = in; + _con = con; + _stmt = stmt; + } + + public void close () throws IOException { + _in.close(); + try { + _con.setAutoCommit(true); + theStorageObject.freeConnection(_con,_stmt); + } catch (Exception e) { + throw new IOException("close(): "+e.toString()); + } + } + + public int read() throws IOException { + return _in.read(); + } + } +} diff --git a/source/mircoders/module/ModuleComment.java b/source/mircoders/module/ModuleComment.java index 35791843..89a8bf07 100755 --- a/source/mircoders/module/ModuleComment.java +++ b/source/mircoders/module/ModuleComment.java @@ -31,11 +31,9 @@ package mircoders.module; -import java.io.PrintWriter; import java.util.Map; import mir.entity.Entity; -import mir.log.LoggerToWriterAdapter; import mir.log.LoggerWrapper; import mir.module.AbstractModule; import mir.module.ModuleException; @@ -104,7 +102,7 @@ public class ModuleComment extends AbstractModule } catch (StorageObjectFailure e){ logger.error("ModuleComment.set: " + e.getMessage()); - e.printStackTrace(logger.asPrintWriter(logger.DEBUG_MESSAGE)); + e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); throw new ModuleException(e.toString()); } catch (StorageObjectExc e) { diff --git a/source/mircoders/producer/IndexingProducerNode.java b/source/mircoders/producer/IndexingProducerNode.java index 74e20ab9..79dc5505 100755 --- a/source/mircoders/producer/IndexingProducerNode.java +++ b/source/mircoders/producer/IndexingProducerNode.java @@ -29,12 +29,10 @@ */ package mircoders.producer; -import java.io.PrintWriter; import java.util.Map; import mir.entity.Entity; import mir.entity.adapter.EntityAdapter; -import mir.log.LoggerToWriterAdapter; import mir.log.LoggerWrapper; import mir.misc.StringUtil; import mir.producer.ProducerFailure; @@ -168,7 +166,7 @@ public class IndexingProducerNode implements ProducerNode { } catch (Throwable t) { aLogger.error("Error while indexing content: " + t.getMessage()); - t.printStackTrace(aLogger.asPrintWriter(aLogger.DEBUG_MESSAGE)); + t.printStackTrace(aLogger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); } finally { if (indexWriter != null) { diff --git a/source/mircoders/producer/PDFGeneratingProducerNode.java b/source/mircoders/producer/PDFGeneratingProducerNode.java index 82327eee..d58add99 100755 --- a/source/mircoders/producer/PDFGeneratingProducerNode.java +++ b/source/mircoders/producer/PDFGeneratingProducerNode.java @@ -71,7 +71,7 @@ public class PDFGeneratingProducerNode implements ProducerNode { } catch (Throwable t) { - t.printStackTrace(aLogger.asPrintWriter(aLogger.DEBUG_MESSAGE)); + t.printStackTrace(aLogger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); aLogger.error(" error while generating: " + t.getMessage() + t.toString()); } endTime = System.currentTimeMillis(); diff --git a/source/mircoders/producer/UnIndexingProducerNode.java b/source/mircoders/producer/UnIndexingProducerNode.java index 05ec4259..35da0bc6 100755 --- a/source/mircoders/producer/UnIndexingProducerNode.java +++ b/source/mircoders/producer/UnIndexingProducerNode.java @@ -31,12 +31,10 @@ package mircoders.producer; -import java.io.PrintWriter; import java.util.Map; import mir.entity.Entity; import mir.entity.adapter.EntityAdapter; -import mir.log.LoggerToWriterAdapter; import mir.log.LoggerWrapper; import mir.producer.ProducerFailure; import mir.producer.ProducerNode; @@ -84,7 +82,7 @@ public class UnIndexingProducerNode implements ProducerNode { } catch (Throwable t) { aLogger.error("Error while unindexing content: " + t.getMessage()); - t.printStackTrace(aLogger.asPrintWriter(aLogger.DEBUG_MESSAGE)); + t.printStackTrace(aLogger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); } endTime = System.currentTimeMillis(); diff --git a/source/mircoders/servlet/ServletHelper.java b/source/mircoders/servlet/ServletHelper.java index a294cce6..c07d68ba 100755 --- a/source/mircoders/servlet/ServletHelper.java +++ b/source/mircoders/servlet/ServletHelper.java @@ -9,9 +9,9 @@ import mir.entity.adapter.EntityIteratorAdapter; import mir.generator.Generator; import mir.servlet.ServletModuleExc; import mir.servlet.ServletModuleFailure; +import mir.util.CachingRewindableIterator; import mir.util.NullWriter; import mir.util.ResourceBundleGeneratorFunction; -import mir.util.CachingRewindableIterator; import mircoders.global.MirGlobal; import org.apache.struts.util.MessageResources; diff --git a/source/mircoders/servlet/ServletModuleAdmin.java b/source/mircoders/servlet/ServletModuleAdmin.java index 88b119df..eb4ae4d9 100755 --- a/source/mircoders/servlet/ServletModuleAdmin.java +++ b/source/mircoders/servlet/ServletModuleAdmin.java @@ -31,13 +31,11 @@ package mircoders.servlet; -import java.io.PrintWriter; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import mir.log.LoggerToWriterAdapter; import mir.log.LoggerWrapper; import mir.servlet.ServletModule; import mir.servlet.ServletModuleFailure; diff --git a/source/mircoders/servlet/ServletModuleBreaking.java b/source/mircoders/servlet/ServletModuleBreaking.java index 0b057a91..b752549c 100755 --- a/source/mircoders/servlet/ServletModuleBreaking.java +++ b/source/mircoders/servlet/ServletModuleBreaking.java @@ -31,7 +31,6 @@ package mircoders.servlet; -import java.io.IOException; import java.net.URLEncoder; import javax.servlet.http.HttpServletRequest; @@ -41,7 +40,6 @@ import mir.config.MirPropertiesConfiguration; import mir.entity.EntityList; import mir.log.LoggerWrapper; import mir.misc.HTMLTemplateProcessor; -import mir.module.ModuleException; import mir.servlet.ServletModule; import mir.servlet.ServletModuleFailure; import mircoders.module.ModuleBreaking; diff --git a/source/mircoders/servlet/ServletModuleComment.java b/source/mircoders/servlet/ServletModuleComment.java index 1e1c652e..510b9844 100755 --- a/source/mircoders/servlet/ServletModuleComment.java +++ b/source/mircoders/servlet/ServletModuleComment.java @@ -31,7 +31,6 @@ package mircoders.servlet; -import java.io.PrintWriter; import java.util.Map; import javax.servlet.http.HttpServletRequest; @@ -40,7 +39,6 @@ import javax.servlet.http.HttpServletResponse; import mir.config.MirPropertiesConfiguration; import mir.entity.adapter.EntityAdapterModel; import mir.entity.adapter.EntityIteratorAdapter; -import mir.log.LoggerToWriterAdapter; import mir.log.LoggerWrapper; import mir.servlet.ServletModule; import mir.servlet.ServletModuleExc; diff --git a/source/mircoders/servlet/ServletModuleContent.java b/source/mircoders/servlet/ServletModuleContent.java index 0300a589..0c5954eb 100755 --- a/source/mircoders/servlet/ServletModuleContent.java +++ b/source/mircoders/servlet/ServletModuleContent.java @@ -1,556 +1,554 @@ -/* - * 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 the com.oreilly.servlet library, 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.util.GregorianCalendar; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import mir.entity.adapter.EntityAdapterModel; -import mir.entity.adapter.EntityIteratorAdapter; -import mir.log.LoggerWrapper; -import mir.misc.StringUtil; -import mir.module.ModuleException; -import mir.servlet.ServletModule; -import mir.servlet.ServletModuleExc; -import mir.servlet.ServletModuleUserExc; -import mir.servlet.ServletModuleFailure; -import mir.storage.StorageObjectFailure; -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.entity.EntityUsers; -import mircoders.global.MirGlobal; -import mircoders.module.ModuleContent; -import mircoders.search.IndexUtil; -import mircoders.storage.DatabaseComment; -import mircoders.storage.DatabaseContent; -import mircoders.storage.DatabaseContentToTopics; - -import org.apache.lucene.index.IndexReader; - -import freemarker.template.SimpleHash; - -/* - * ServletModuleContent - - * deliver html for the article admin form. - * - * @version $Id: ServletModuleContent.java,v 1.40 2003/03/06 05:40:40 zapata Exp $ - * @author rk, mir-coders - * - */ - -public class ServletModuleContent extends ServletModule -{ - private String editTemplate = configuration.getString("ServletModule.Content.ObjektTemplate");; - private String listTemplate = configuration.getString("ServletModule.Content.ListTemplate"); - - private static ServletModuleContent instance = new ServletModuleContent(); - public static ServletModule getInstance() { return instance; } - - private ServletModuleContent() { - super(); - logger = new LoggerWrapper("ServletModule.Content"); - try { - - templateListString = configuration.getString("ServletModule.Content.ListTemplate"); - templateObjektString = configuration.getString("ServletModule.Content.ObjektTemplate"); - templateConfirmString = configuration.getString("ServletModule.Content.ConfirmTemplate"); - - mainModule = new ModuleContent(DatabaseContent.getInstance()); - } - catch (StorageObjectFailure e) { - logger.error("servletmodulecontent konnte nicht initialisiert werden"); - } - } - - 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("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.appendAscendingOrder("webdb_create"); - else if (searchOrder.equals("dateasc")) - queryBuilder.appendDescendingOrder("webdb_create"); - else if (searchOrder.equals("title")) - queryBuilder.appendDescendingOrder("title"); - else if (searchOrder.equals("creator")) - queryBuilder.appendDescendingOrder("creator"); - } - - returnArticleList(aRequest, aResponse, queryBuilder.getWhereClause(), queryBuilder.getOrderByClause(), 0, selectArticleUrl); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - public void add(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc { - _showObject(null, req, res); - } - - - public void insert(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc - { -//theLog.printDebugInfo(":: content :: trying to insert"); - try { - EntityUsers user = _getUser(req); - Map withValues = getIntersectingValues(req, DatabaseContent.getInstance()); - - String now = StringUtil.date2webdbDate(new GregorianCalendar()); - withValues.put("date", now); - withValues.put("publish_path", StringUtil.webdbDate2path(now)); - withValues.put("to_publisher", user.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 id = mainModule.add(withValues); - DatabaseContentToTopics.getInstance().setTopics(id,req.getParameterValues("to_topic")); - - _showObject(id, req, res); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - public void delete(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc - { - EntityUsers user = _getUser(req); - - String idParam = req.getParameter("id"); - if (idParam == null) throw new ServletModuleExc("Invalid call: id missing"); - - String confirmParam = req.getParameter("confirm"); - String cancelParam = req.getParameter("cancel"); - - logger.info("where = " + req.getParameter("where")); - - if (confirmParam == null && cancelParam == null) { - - SimpleHash mergeData = new SimpleHash(); - mergeData.put("module", "Content"); - mergeData.put("infoString", "Content: " + idParam); - mergeData.put("id", idParam); - mergeData.put("where", req.getParameter("where")); - mergeData.put("order", req.getParameter("order")); - mergeData.put("offset", req.getParameter("offset")); - deliver(req, res, mergeData, templateConfirmString); - } - else { - if (confirmParam!= null && !confirmParam.equals("")) { - try { - mainModule.deleteById(idParam); - - /** @todo the following two should be implied in - * DatabaseContent */ - - //delete rows in the content_x_topic-table - DatabaseContentToTopics.getInstance().deleteByContentId(idParam); - //delete rows in the comment-table - DatabaseComment.getInstance().deleteByContentId(idParam); - //delete from lucene index, if any - String index = configuration.getString("IndexPath"); - if (IndexReader.indexExists(index)){ - IndexUtil.unindexID(idParam,index); - } - - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - list(req,res); - } - else { - // Datensatz anzeigen - _showObject(idParam, req, res); - } - } - } - - public void edit(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc - { - String idParam = req.getParameter("id"); - if (idParam == null) - throw new ServletModuleExc("Invalid call: id not supplied "); - _showObject(idParam, req, res); - } - -// methods for attaching media file - public void attach(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc - { - String mediaIdParam = req.getParameter("mid"); - String idParam = req.getParameter("cid"); - if (idParam == null||mediaIdParam==null) throw new ServletModuleExc("smod content :: attach :: cid/mid missing"); - - try { - EntityContent entContent = (EntityContent)mainModule.getById(idParam); - entContent.attach(mediaIdParam); - } - catch(ModuleException e) { - logger.error("smod content :: attach :: could not get entityContent"); - } - catch(StorageObjectFailure e) { - logger.error("smod content :: attach :: could not get entityContent"); - } - - _showObject(idParam, req, res); - } - - public void dettach(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc - { - String cidParam = req.getParameter("cid"); - String midParam = req.getParameter("mid"); - if (cidParam == null) - throw new ServletModuleExc("smod content :: dettach :: cid missing"); - if (midParam == null) - throw new ServletModuleExc("smod content :: dettach :: mid missing"); - - try { - EntityContent entContent = (EntityContent)mainModule.getById(cidParam); - entContent.dettach(cidParam,midParam); - } - catch(ModuleException e) { - logger.error("smod content :: dettach :: could not get entityContent"); - } - catch(StorageObjectFailure e) { - logger.error("smod content :: dettach :: could not get entityContent"); - } - - _showObject(cidParam, req, res); - } - - 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[] topic_id = aRequest.getParameterValues("to_topic"); - 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 id = mainModule.set(withValues); - DatabaseContentToTopics.getInstance().setTopics(aRequest.getParameter("id"),topic_id); - - String whereParam = aRequest.getParameter("where"); - String orderParam = aRequest.getParameter("order"); - - if (returnUrl!=null){ - 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. -*/ - public void _showObject(String id, HttpServletRequest aRequest, HttpServletResponse aResponse) - throws ServletModuleExc { - try { - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - Map responseData = ServletHelper.makeGenerationData(getLocale(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("returnurl", requestParser.getParameter("returnurl")); - responseData.put("thisurl", urlBuilder.getQuery()); - - ServletHelper.generateResponse(aResponse.getWriter(), responseData, editTemplate); - } - 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 nrArticlesPerPage = 20; - int count; - - try { - Map responseData = ServletHelper.makeGenerationData(getLocale(aRequest)); - model = MirGlobal.localizer().dataModel().adapterModel(); - - Object articleList = - new CachingRewindableIterator( - new EntityIteratorAdapter( aWhereClause, anOrderByClause, nrArticlesPerPage, - MirGlobal.localizer().dataModel().adapterModel(), "content", nrArticlesPerPage, 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+nrArticlesPerPage) { - urlBuilder.setValue("offset", (anOffset + nrArticlesPerPage)); - responseData.put("nexturl" , urlBuilder.getQuery()); - } - - if (anOffset>0) { - urlBuilder.setValue("offset", Math.max(anOffset - nrArticlesPerPage, 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+nrArticlesPerPage, count))); - responseData.put("offset" , Integer.toString(anOffset)); - responseData.put("order", anOrderByClause); - responseData.put("where" , aWhereClause); - - ServletHelper.generateResponse(aResponse.getWriter(), responseData, listTemplate); - } - 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); - } - - private EntityUsers _getUser(HttpServletRequest req) - { - HttpSession session=req.getSession(false); - - return (EntityUsers)session.getAttribute("login.uid"); - } -} +/* + * 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 the com.oreilly.servlet library, 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.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import mir.entity.adapter.EntityAdapterModel; +import mir.entity.adapter.EntityIteratorAdapter; +import mir.log.LoggerWrapper; +import mir.misc.StringUtil; +import mir.module.ModuleException; +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 mir.util.SQLQueryBuilder; +import mir.util.URLBuilder; +import mircoders.entity.EntityContent; +import mircoders.entity.EntityUsers; +import mircoders.global.MirGlobal; +import mircoders.module.ModuleContent; +import mircoders.search.IndexUtil; +import mircoders.storage.DatabaseComment; +import mircoders.storage.DatabaseContent; +import mircoders.storage.DatabaseContentToTopics; + +import org.apache.lucene.index.IndexReader; + +import freemarker.template.SimpleHash; + +/* + * ServletModuleContent - + * deliver html for the article admin form. + * + * @version $Id: ServletModuleContent.java,v 1.41 2003/03/08 17:18:19 idfx Exp $ + * @author rk, mir-coders + * + */ + +public class ServletModuleContent extends ServletModule +{ + private String editTemplate = configuration.getString("ServletModule.Content.ObjektTemplate");; + private String listTemplate = configuration.getString("ServletModule.Content.ListTemplate"); + + private static ServletModuleContent instance = new ServletModuleContent(); + public static ServletModule getInstance() { return instance; } + + private ServletModuleContent() { + super(); + logger = new LoggerWrapper("ServletModule.Content"); + try { + + templateListString = configuration.getString("ServletModule.Content.ListTemplate"); + templateObjektString = configuration.getString("ServletModule.Content.ObjektTemplate"); + templateConfirmString = configuration.getString("ServletModule.Content.ConfirmTemplate"); + + mainModule = new ModuleContent(DatabaseContent.getInstance()); + } + catch (StorageObjectFailure e) { + logger.error("servletmodulecontent konnte nicht initialisiert werden"); + } + } + + 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("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.appendAscendingOrder("webdb_create"); + else if (searchOrder.equals("dateasc")) + queryBuilder.appendDescendingOrder("webdb_create"); + else if (searchOrder.equals("title")) + queryBuilder.appendDescendingOrder("title"); + else if (searchOrder.equals("creator")) + queryBuilder.appendDescendingOrder("creator"); + } + + returnArticleList(aRequest, aResponse, queryBuilder.getWhereClause(), queryBuilder.getOrderByClause(), 0, selectArticleUrl); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + public void add(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc { + _showObject(null, req, res); + } + + + public void insert(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc + { +//theLog.printDebugInfo(":: content :: trying to insert"); + try { + EntityUsers user = _getUser(req); + Map withValues = getIntersectingValues(req, DatabaseContent.getInstance()); + + String now = StringUtil.date2webdbDate(new GregorianCalendar()); + withValues.put("date", now); + withValues.put("publish_path", StringUtil.webdbDate2path(now)); + withValues.put("to_publisher", user.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 id = mainModule.add(withValues); + DatabaseContentToTopics.getInstance().setTopics(id,req.getParameterValues("to_topic")); + + _showObject(id, req, res); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + public void delete(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc + { + EntityUsers user = _getUser(req); + + String idParam = req.getParameter("id"); + if (idParam == null) throw new ServletModuleExc("Invalid call: id missing"); + + String confirmParam = req.getParameter("confirm"); + String cancelParam = req.getParameter("cancel"); + + logger.info("where = " + req.getParameter("where")); + + if (confirmParam == null && cancelParam == null) { + + SimpleHash mergeData = new SimpleHash(); + mergeData.put("module", "Content"); + mergeData.put("infoString", "Content: " + idParam); + mergeData.put("id", idParam); + mergeData.put("where", req.getParameter("where")); + mergeData.put("order", req.getParameter("order")); + mergeData.put("offset", req.getParameter("offset")); + deliver(req, res, mergeData, templateConfirmString); + } + else { + if (confirmParam!= null && !confirmParam.equals("")) { + try { + mainModule.deleteById(idParam); + + /** @todo the following two should be implied in + * DatabaseContent */ + + //delete rows in the content_x_topic-table + DatabaseContentToTopics.getInstance().deleteByContentId(idParam); + //delete rows in the comment-table + DatabaseComment.getInstance().deleteByContentId(idParam); + //delete from lucene index, if any + String index = configuration.getString("IndexPath"); + if (IndexReader.indexExists(index)){ + IndexUtil.unindexID(idParam,index); + } + + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + list(req,res); + } + else { + // Datensatz anzeigen + _showObject(idParam, req, res); + } + } + } + + public void edit(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc + { + String idParam = req.getParameter("id"); + if (idParam == null) + throw new ServletModuleExc("Invalid call: id not supplied "); + _showObject(idParam, req, res); + } + +// methods for attaching media file + public void attach(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc + { + String mediaIdParam = req.getParameter("mid"); + String idParam = req.getParameter("cid"); + if (idParam == null||mediaIdParam==null) throw new ServletModuleExc("smod content :: attach :: cid/mid missing"); + + try { + EntityContent entContent = (EntityContent)mainModule.getById(idParam); + entContent.attach(mediaIdParam); + } + catch(ModuleException e) { + logger.error("smod content :: attach :: could not get entityContent"); + } + catch(StorageObjectFailure e) { + logger.error("smod content :: attach :: could not get entityContent"); + } + + _showObject(idParam, req, res); + } + + public void dettach(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc + { + String cidParam = req.getParameter("cid"); + String midParam = req.getParameter("mid"); + if (cidParam == null) + throw new ServletModuleExc("smod content :: dettach :: cid missing"); + if (midParam == null) + throw new ServletModuleExc("smod content :: dettach :: mid missing"); + + try { + EntityContent entContent = (EntityContent)mainModule.getById(cidParam); + entContent.dettach(cidParam,midParam); + } + catch(ModuleException e) { + logger.error("smod content :: dettach :: could not get entityContent"); + } + catch(StorageObjectFailure e) { + logger.error("smod content :: dettach :: could not get entityContent"); + } + + _showObject(cidParam, req, res); + } + + 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[] topic_id = aRequest.getParameterValues("to_topic"); + 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 id = mainModule.set(withValues); + DatabaseContentToTopics.getInstance().setTopics(aRequest.getParameter("id"),topic_id); + + String whereParam = aRequest.getParameter("where"); + String orderParam = aRequest.getParameter("order"); + + if (returnUrl!=null){ + 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. +*/ + public void _showObject(String id, HttpServletRequest aRequest, HttpServletResponse aResponse) + throws ServletModuleExc { + try { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + Map responseData = ServletHelper.makeGenerationData(getLocale(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("returnurl", requestParser.getParameter("returnurl")); + responseData.put("thisurl", urlBuilder.getQuery()); + + ServletHelper.generateResponse(aResponse.getWriter(), responseData, editTemplate); + } + 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 nrArticlesPerPage = 20; + int count; + + try { + Map responseData = ServletHelper.makeGenerationData(getLocale(aRequest)); + model = MirGlobal.localizer().dataModel().adapterModel(); + + Object articleList = + new CachingRewindableIterator( + new EntityIteratorAdapter( aWhereClause, anOrderByClause, nrArticlesPerPage, + MirGlobal.localizer().dataModel().adapterModel(), "content", nrArticlesPerPage, 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+nrArticlesPerPage) { + urlBuilder.setValue("offset", (anOffset + nrArticlesPerPage)); + responseData.put("nexturl" , urlBuilder.getQuery()); + } + + if (anOffset>0) { + urlBuilder.setValue("offset", Math.max(anOffset - nrArticlesPerPage, 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+nrArticlesPerPage, count))); + responseData.put("offset" , Integer.toString(anOffset)); + responseData.put("order", anOrderByClause); + responseData.put("where" , aWhereClause); + + ServletHelper.generateResponse(aResponse.getWriter(), responseData, listTemplate); + } + 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); + } + + private EntityUsers _getUser(HttpServletRequest req) + { + HttpSession session=req.getSession(false); + + return (EntityUsers)session.getAttribute("login.uid"); + } +} diff --git a/source/mircoders/servlet/ServletModuleFileEdit.java b/source/mircoders/servlet/ServletModuleFileEdit.java index c93712e5..251e1a02 100755 --- a/source/mircoders/servlet/ServletModuleFileEdit.java +++ b/source/mircoders/servlet/ServletModuleFileEdit.java @@ -34,7 +34,6 @@ package mircoders.servlet; import java.io.File; import java.io.FileReader; import java.io.FileWriter; -import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; @@ -55,8 +54,8 @@ import freemarker.template.SimpleList; * Allows one to do a basic edit of a file in a directory specified * in the config file. * - * @author $Author: zapata $ - * @version $Revision: 1.6 $ $Date: 2003/03/06 05:40:40 $ + * @author $Author: idfx $ + * @version $Revision: 1.7 $ $Date: 2003/03/08 17:18:19 $ * */ diff --git a/source/mircoders/servlet/ServletModuleHidden.java b/source/mircoders/servlet/ServletModuleHidden.java index bae412b8..b7a63584 100755 --- a/source/mircoders/servlet/ServletModuleHidden.java +++ b/source/mircoders/servlet/ServletModuleHidden.java @@ -31,15 +31,12 @@ package mircoders.servlet; -import java.io.IOException; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import mir.entity.EntityList; import mir.log.LoggerWrapper; import mir.misc.HTMLTemplateProcessor; -import mir.module.ModuleException; import mir.servlet.ServletModule; import mir.servlet.ServletModuleExc; import mir.servlet.ServletModuleFailure; diff --git a/source/mircoders/servlet/ServletModuleLinksImcs.java b/source/mircoders/servlet/ServletModuleLinksImcs.java index dc740ea3..e854dcd5 100755 --- a/source/mircoders/servlet/ServletModuleLinksImcs.java +++ b/source/mircoders/servlet/ServletModuleLinksImcs.java @@ -31,7 +31,6 @@ package mircoders.servlet; -import java.io.IOException; import java.io.PrintWriter; import java.net.URLEncoder; @@ -40,9 +39,7 @@ import javax.servlet.http.HttpServletResponse; import mir.entity.EntityList; import mir.log.LoggerWrapper; -import mir.misc.HTMLParseException; import mir.misc.HTMLTemplateProcessor; -import mir.module.ModuleException; import mir.servlet.ServletModule; import mir.servlet.ServletModuleExc; import mir.servlet.ServletModuleFailure; diff --git a/source/mircoders/servlet/ServletModuleMessage.java b/source/mircoders/servlet/ServletModuleMessage.java index fbe12e93..cedb77a5 100755 --- a/source/mircoders/servlet/ServletModuleMessage.java +++ b/source/mircoders/servlet/ServletModuleMessage.java @@ -31,7 +31,6 @@ package mircoders.servlet; -import java.io.IOException; import java.net.URLEncoder; import javax.servlet.http.HttpServletRequest; @@ -40,7 +39,6 @@ import javax.servlet.http.HttpServletResponse; import mir.entity.EntityList; import mir.log.LoggerWrapper; import mir.misc.HTMLTemplateProcessor; -import mir.module.ModuleException; import mir.servlet.ServletModule; import mir.servlet.ServletModuleExc; import mir.servlet.ServletModuleFailure; diff --git a/source/mircoders/servlet/ServletModuleOpenIndy.java b/source/mircoders/servlet/ServletModuleOpenIndy.java index beb854b7..d787df6f 100755 --- a/source/mircoders/servlet/ServletModuleOpenIndy.java +++ b/source/mircoders/servlet/ServletModuleOpenIndy.java @@ -1,984 +1,981 @@ -/* - * 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 the com.oreilly.servlet library, 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.ByteArrayOutputStream; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.Iterator; -import java.util.ListIterator; -import java.util.Locale; -import java.util.Map; -import java.util.Random; -import java.util.Set; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import mir.config.MirPropertiesConfiguration.PropertiesConfigExc; -import mir.entity.Entity; -import mir.entity.EntityList; -import mir.log.LoggerWrapper; -import mir.misc.FileHandler; -import mir.misc.FileHandlerException; -import mir.misc.FileHandlerUserException; -import mir.misc.HTMLParseException; -import mir.misc.HTMLTemplateProcessor; -import mir.misc.StringUtil; -import mir.misc.WebdbMultipartRequest; -import mir.module.ModuleException; -import mir.servlet.ServletModule; -import mir.servlet.ServletModuleExc; -import mir.servlet.ServletModuleUserExc; -import mir.servlet.ServletModuleFailure; -import mir.storage.StorageObjectFailure; -import mir.util.StringRoutines; -import mircoders.entity.EntityComment; -import mircoders.entity.EntityContent; -import mircoders.global.MirGlobal; -import mircoders.media.MediaRequest; -import mircoders.module.ModuleComment; -import mircoders.module.ModuleContent; -import mircoders.module.ModuleImages; -import mircoders.module.ModuleTopics; -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.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 org.apache.commons.net.smtp.SMTPClient; -import org.apache.commons.net.smtp.SMTPReply; -import org.apache.fop.apps.Driver; -import org.apache.fop.apps.XSLTInputHandler; -import org.apache.log.Hierarchy; -import org.apache.log.Priority; -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 freemarker.template.SimpleHash; -import freemarker.template.SimpleList; -import freemarker.template.SimpleScalar; -import freemarker.template.TemplateModelRoot; - -/* - * ServletModuleOpenIndy - - * is the open-access-servlet, which is responsible for - * adding comments to articles & - * open-postings to the newswire - * - * @author mir-coders group - * @version $Id: ServletModuleOpenIndy.java,v 1.63 2003/03/06 05:40:40 zapata Exp $ - * - */ - -public class ServletModuleOpenIndy extends ServletModule -{ - - private String commentFormTemplate, commentFormDoneTemplate, - commentFormDupeTemplate; - private String postingFormTemplate, postingFormDoneTemplate, - postingFormDupeTemplate; - private String searchResultsTemplate; - private String prepareMailTemplate,sentMailTemplate; - private ModuleContent contentModule; - private ModuleComment commentModule; - private ModuleImages imageModule; - private ModuleTopics themenModule; - private String directOp ="yes"; - private String passwdProtection ="yes"; - // Singelton / Kontruktor - private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy(); - public static ServletModule getInstance() { return instance; } - - private ServletModuleOpenIndy() { - super(); - try { - logger = new LoggerWrapper("ServletModule.OpenIndy"); - - commentFormTemplate = configuration.getString("ServletModule.OpenIndy.CommentTemplate"); - commentFormDoneTemplate = configuration.getString("ServletModule.OpenIndy.CommentDoneTemplate"); - commentFormDupeTemplate = configuration.getString("ServletModule.OpenIndy.CommentDupeTemplate"); - postingFormTemplate = configuration.getString("ServletModule.OpenIndy.PostingTemplate"); - postingFormDoneTemplate = configuration.getString("ServletModule.OpenIndy.PostingDoneTemplate"); - postingFormDupeTemplate = configuration.getString("ServletModule.OpenIndy.PostingDupeTemplate"); - searchResultsTemplate = configuration.getString("ServletModule.OpenIndy.SearchResultsTemplate"); - prepareMailTemplate = configuration.getString("ServletModule.OpenIndy.PrepareMailTemplate"); - sentMailTemplate = configuration.getString("ServletModule.OpenIndy.SentMailTemplate"); - directOp = configuration.getString("DirectOpenposting").toLowerCase(); - passwdProtection = configuration.getString("PasswdProtection").toLowerCase(); - mainModule = new ModuleComment(DatabaseComment.getInstance()); - contentModule = new ModuleContent(DatabaseContent.getInstance()); - themenModule = new ModuleTopics(DatabaseTopics.getInstance()); - imageModule = new ModuleImages(DatabaseImages.getInstance()); - defaultAction="addposting"; - - } - catch (StorageObjectFailure e) { - logger.error("servletmoduleopenindy could not be initialized: " + e.getMessage()); - } - } - - - /** - * Method for making a comment - */ - - public void addcomment(HttpServletRequest req, HttpServletResponse res) - throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure - { - String aid = req.getParameter("aid"); // the article id the comment will belong to - String language = req.getParameter("language"); - - if (aid!=null && !aid.equals("")) { - try { - SimpleHash mergeData = new SimpleHash(); - - // onetimepasswd - if (passwdProtection.equals("yes")) { - String passwd = this.createOneTimePasswd(); - HttpSession session = req.getSession(false); - session.setAttribute("passwd", passwd); - mergeData.put("passwd", passwd); - } - - if (language != null) { - HttpSession session = req.getSession(false); - session.setAttribute("Locale", new Locale(language, "")); - session.setAttribute("passwd", language); - } - - mergeData.put("aid", aid); - - SimpleHash extraInfo = new SimpleHash(); - extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData()); - - deliver(req, res, mergeData, extraInfo, commentFormTemplate); - } - catch (Throwable t) { - throw new ServletModuleFailure("ServletModuleOpenIndy.addcomment: " + t.getMessage(), t); - } - } - else throw new ServletModuleExc("aid not set!"); - } - - /** - * Method for inserting a comment into the Database and delivering - * the commentDone Page - */ - - public void inscomment(HttpServletRequest req, HttpServletResponse res) - throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure - { - String aid = req.getParameter("to_media"); // the article id the comment will belong to - if (aid!=null && !aid.equals("")) - { - // ok, collecting data from form - try { - Map withValues = getIntersectingValues(req, DatabaseComment.getInstance()); - - //no html in comments(for now) - for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){ - String k=(String)i.next(); - String v=(String)withValues.get(k); - - withValues.put(k,StringUtil.removeHTMLTags(v)); - } - withValues.put("is_published","1"); - withValues.put("to_comment_status","1"); - - //checking the onetimepasswd - if(passwdProtection.equals("yes")){ - HttpSession session = req.getSession(false); - String sessionPasswd = (String)session.getAttribute("passwd"); - if ( sessionPasswd == null){ - throw new ServletModuleUserExc("Lost password"); - } - String passwd = req.getParameter("passwd"); - if ( passwd == null || (!sessionPasswd.equals(passwd))) { - throw new ServletModuleUserExc("Missing password"); - } - session.invalidate(); - } - - // inserting into database - String id = mainModule.add(withValues); - logger.debug("id: "+id); - //insert was not successfull - if(id==null){ - deliver(req, res, new SimpleHash(), commentFormDupeTemplate); - } else { - DatabaseContent.getInstance().setUnproduced("id="+aid); - - try { - EntityComment comment = (EntityComment) DatabaseComment.getInstance().selectById(id); - MirGlobal.localizer().openPostings().afterCommentPosting(comment); - } - catch (Throwable t) { - throw new ServletModuleExc(t.getMessage()); - } - } - - // redirecting to url - // should implement back to article - SimpleHash mergeData = new SimpleHash(); - deliver(req, res, mergeData, commentFormDoneTemplate); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - else throw new ServletModuleExc("aid not set!"); - - } - - /** - * Method for delivering the form-Page for open posting - */ - - public void addposting(HttpServletRequest req, HttpServletResponse res) - throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure - { - SimpleHash mergeData = new SimpleHash(); - - // onetimepasswd - if(passwdProtection.equals("yes")){ - String passwd = this.createOneTimePasswd(); - HttpSession session = req.getSession(false); - session.setAttribute("passwd",passwd); - mergeData.put("passwd", passwd); - } - - String maxMedia = configuration.getString("ServletModule.OpenIndy.MaxMediaUploadItems"); - String defaultMedia = configuration.getString("ServletModule.OpenIndy.DefaultMediaUploadItems"); - String numOfMedia = req.getParameter("medianum"); - - if(numOfMedia==null||numOfMedia.equals("")){ - numOfMedia=defaultMedia; - } - else if(Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) { - numOfMedia = maxMedia; - } - - int mediaNum = Integer.parseInt(numOfMedia); - SimpleList mediaFields = new SimpleList(); - for(int i =0; i 0) { - try{ - DatabaseContentToTopics.getInstance().setTopics(cid,to_topicsArr); - setTopic = true; - } - catch (Exception e) { - logger.error("setting content_x_topic failed"); - contentModule.deleteById(cid); - throw new ServletModuleExc("smod - openindy :: insposting: setting content_x_topic failed: "+e.toString()); - } //end try - } //end if - - //if we're here all is ok... associate the media to the article - for(int i=0;i= totalHits) - newPosition=totalHits-1; - session.setAttribute("positionInResults",new Integer(newPosition)); - } - else { - if (searchForwardValue != null){ - int totalHits = ((Integer) session.getAttribute("numberOfHits")).intValue(); - int newPosition=((Integer)session.getAttribute("positionInResults")).intValue()+increment; - if (newPosition<0) - newPosition=0; - if (newPosition >= totalHits) - newPosition=totalHits-1; - - session.setAttribute("positionInResults",new Integer(newPosition)); - } - else { - String indexPath=configuration.getString("IndexPath"); - - - String creatorFragment = creatorTerm.makeTerm(req); - if (creatorFragment != null){ - queryString = queryString + " +" + creatorFragment; - } - - // search title, description, and content for something - // the contentTerm uses param "search_boolean" to combine its terms - String contentFragment = contentTerm.makeTerm(req); - if (contentFragment != null){ - logger.debug("contentFragment: " + contentFragment); - queryString = queryString + " +" + contentFragment; - } - - String topicFragment = topicTerm.makeTerm(req); - if (topicFragment != null){ - queryString = queryString + " +" + topicFragment; - } - - String imagesFragment = imagesTerm.makeTerm(req); - if (imagesFragment != null){ - queryString = queryString + " +" + imagesFragment; - } - - String audioFragment = audioTerm.makeTerm(req); - if (audioFragment != null){ - queryString = queryString + " +" + audioFragment; - } - - String videoFragment = videoTerm.makeTerm(req); - if (videoFragment != null){ - queryString = queryString + " +" + videoFragment; - } - - if (queryString == null || queryString == ""){ - queryString = ""; - } - else{ - try{ - Searcher searcher = null; - try { - searcher = new IndexSearcher(indexPath); - } - catch(IOException e) { - logger.debug("Can't open indexPath: " + indexPath); - throw new ServletModuleExc("Problem with Search Index! : "+ e.toString()); - } - - Query query = null; - try { - query = QueryParser.parse(queryString, "content", new StandardAnalyzer()); - } - catch(Exception e) { - searcher.close(); - logger.debug("Query don't parse: " + queryString); - throw new ServletModuleExc("Problem with Query String! (was '"+queryString+"')"); - } - - Hits hits = null; - try { - hits = searcher.search(query); - } - catch(IOException e) { - searcher.close(); - logger.debug("Can't get hits: " + e.toString()); - throw new ServletModuleExc("Problem getting hits!"); - } - - int start = 0; - int end = hits.length(); - - String sortBy=req.getParameter("search_sort"); - if (sortBy == null || sortBy.equals("")){ - throw new ServletModuleExc("Please let me sort by something!(missing search_sort)"); - } - - // here is where the documents will go for storage across sessions - ArrayList theDocumentsSorted = new ArrayList(); - - if (sortBy.equals("score")){ - for(int i = start; i < end; i++) { - theDocumentsSorted.add(hits.doc(i)); - } - } - else{ - // then we'll sort by date! - Map dateToPosition = new HashMap(end,1.0F); //we know how big it will be - for(int i = start; i < end; i++) { - String creationDate=(hits.doc(i)).get("creationDate"); - // do a little dance in case two contents created at the same second! - if (dateToPosition.containsKey(creationDate)){ - ((ArrayList) (dateToPosition.get(creationDate))).add(new Integer(i)); - } - else{ - ArrayList thePositions = new ArrayList(); - thePositions.add(new Integer(i)); - dateToPosition.put(creationDate,thePositions); - } - } - Set keys = dateToPosition.keySet(); - ArrayList keyList= new ArrayList(keys); - Collections.sort(keyList); - if (sortBy.equals("date_desc")){ - Collections.reverse(keyList); - } - else{ - if (!sortBy.equals("date_asc")){ - throw new ServletModuleExc("don't know how to sort by: "+ sortBy); - } - } - ListIterator keyTraverser = keyList.listIterator(); - while (keyTraverser.hasNext()){ - ArrayList positions = (ArrayList)dateToPosition.get((keyTraverser.next())); - ListIterator positionsTraverser=positions.listIterator(); - while (positionsTraverser.hasNext()){ - theDocumentsSorted.add(hits.doc(((Integer)(positionsTraverser.next())).intValue())); - } - } - } - - try{ - searcher.close(); - } - catch (IOException e){ - logger.debug("Can't close searcher: " + e.toString()); - throw new ServletModuleFailure("Problem closing searcher(normal):" + e.getMessage(), e); - } - - - session.removeAttribute("numberOfHits"); - session.removeAttribute("theDocumentsSorted"); - session.removeAttribute("positionInResults"); - - session.setAttribute("numberOfHits",new Integer(end)); - session.setAttribute("theDocumentsSorted",theDocumentsSorted); - session.setAttribute("positionInResults",new Integer(0)); - - } - catch (IOException e){ - logger.debug("Can't close searcher: " + e.toString()); - throw new ServletModuleFailure("Problem closing searcher: " + e.getMessage(), e); - } - } - } - } - - try { - ArrayList theDocs = (ArrayList)session.getAttribute("theDocumentsSorted"); - if (theDocs != null){ - - mergeData.put("numberOfHits", ((Integer)session.getAttribute("numberOfHits")).toString()); - SimpleList theHits = new SimpleList(); - int pIR=((Integer)session.getAttribute("positionInResults")).intValue(); - int terminus; - int numHits=((Integer)session.getAttribute("numberOfHits")).intValue(); - - if (!(pIR+increment>=numHits)){ - mergeData.put("hasNext","y"); - } - if (pIR>0){ - mergeData.put("hasPrevious","y"); - } - - if ((pIR+increment)>numHits){ - terminus=numHits; - } - else { - terminus=pIR+increment; - } - for(int i = pIR; i < terminus; i++) { - SimpleHash h = new SimpleHash(); - Document theHit = (Document)theDocs.get(i); - whereTerm.returnMeta(h,theHit); - creatorTerm.returnMeta(h,theHit); - titleTerm.returnMeta(h,theHit); - descriptionTerm.returnMeta(h,theHit); - dateTerm.returnMeta(h,theHit); - imagesTerm.returnMeta(h,theHit); - audioTerm.returnMeta(h,theHit); - videoTerm.returnMeta(h,theHit); - theHits.add(h); - } - mergeData.put("hits",theHits); - } - } - catch (Throwable e) { - logger.error("Can't iterate over hits: " + e.toString()); - - throw new ServletModuleFailure("Problem getting hits: " + e.getMessage(), e); - } - - mergeData.put("queryString",queryString); - deliver(req,res,mergeData,searchResultsTemplate); - } - catch (NullPointerException n){ - throw new ServletModuleFailure("Null Pointer: "+n.toString(), n); - } - } - - /* - * Method for dynamically generating a pdf from a fo file - */ - public void getpdf(HttpServletRequest req, HttpServletResponse res) - throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { - String ID_REQUEST_PARAM = "id"; - String language = req.getParameter("language"); - String generateFO=configuration.getString("GenerateFO"); - String generatePDF=configuration.getString("GeneratePDF"); - - - //don't do anything if we are not making FO files, or if we are - //pregenerating PDF's - if (generateFO.equals("yes") && generatePDF.equals("no")){ - //fop complains unless you do the logging this way - org.apache.log.Logger log = null; - Hierarchy hierarchy = Hierarchy.getDefaultHierarchy(); - log = hierarchy.getLoggerFor("fop"); - log.setPriority(Priority.WARN); - - String producerStorageRoot=configuration.getString("Producer.StorageRoot"); - String producerDocRoot=configuration.getString("Producer.DocRoot"); - // String templateDir=MirConfig.getPropWithHome("HTMLTemplateProcessor.Dir"); - String xslSheet=configuration.getString("Producer.HTML2FOStyleSheet"); - try { - String idParam = req.getParameter(ID_REQUEST_PARAM); - if (idParam != null) { - EntityContent contentEnt = - (EntityContent)contentModule.getById(idParam); - String publishPath = StringUtil.webdbDate2path(contentEnt.getValue("date")); - String foFile; - - if (language == null){ - foFile = producerStorageRoot + producerDocRoot + "/" - + publishPath + idParam + ".fo"; - } - else{ - foFile = producerStorageRoot + producerDocRoot + "/" - + language + publishPath + idParam + ".fo"; - } - logger.debug("USING FILES" + foFile + " and " + xslSheet); - XSLTInputHandler input = new XSLTInputHandler(new File(foFile), - new File(xslSheet)); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - res.setContentType("application/pdf"); - - Driver driver = new Driver(); - driver.setLogger(log); - driver.setRenderer(Driver.RENDER_PDF); - driver.setOutputStream(out); - driver.render(input.getParser(), input.getInputSource()); - - byte[] content = out.toByteArray(); - res.setContentLength(content.length); - res.getOutputStream().write(content); - res.getOutputStream().flush(); - } - else { - throw new ServletModuleUserExc("Missing id parameter."); - } - } - catch (Exception ex) { - logger.error(ex.toString()); - throw new ServletModuleFailure(ex); - } - } else { - throw new ServletModuleExc("Can't generate a PDF because the config tells me not to."); - } - } - - private void _throwBadContentType (String fileName, String contentType) - throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { - - logger.error("Wrong file type uploaded!: " + fileName+" " - +contentType); - throw new ServletModuleUserExc("The file you uploaded is of the " - +"following mime-type: "+contentType - +", we do not support this mime-type. " - +"Error One or more files of unrecognized type. Sorry"); - } - - protected String createOneTimePasswd(){ - Random r = new Random(); - int random = r.nextInt(); - long l = System.currentTimeMillis(); - l = (l*l*l*l)/random; - if(l<0) l = l * -1; - String returnString = ""+l; - return returnString.substring(5); - } - - - /* this is an overwritten method of ServletModule in order - to use different bundles for open and admin */ - public void deliver(HttpServletRequest req, HttpServletResponse res, - TemplateModelRoot rtm, TemplateModelRoot popups, - String templateFilename) throws ServletModuleFailure - { - if (rtm == null) rtm = new SimpleHash(); - try { - PrintWriter out = res.getWriter(); - HTMLTemplateProcessor.process(res, templateFilename, rtm, popups, out, - getLocale(req), "bundles.open"); - out.close(); - } - 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 the com.oreilly.servlet library, 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.ByteArrayOutputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Enumeration; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.Iterator; +import java.util.ListIterator; +import java.util.Locale; +import java.util.Map; +import java.util.Random; +import java.util.Set; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import mir.entity.Entity; +import mir.entity.EntityList; +import mir.log.LoggerWrapper; +import mir.misc.FileHandler; +import mir.misc.FileHandlerUserException; +import mir.misc.HTMLTemplateProcessor; +import mir.misc.StringUtil; +import mir.misc.WebdbMultipartRequest; +import mir.module.ModuleException; +import mir.servlet.ServletModule; +import mir.servlet.ServletModuleExc; +import mir.servlet.ServletModuleFailure; +import mir.servlet.ServletModuleUserExc; +import mir.storage.StorageObjectFailure; +import mir.util.StringRoutines; +import mircoders.entity.EntityComment; +import mircoders.entity.EntityContent; +import mircoders.global.MirGlobal; +import mircoders.media.MediaRequest; +import mircoders.module.ModuleComment; +import mircoders.module.ModuleContent; +import mircoders.module.ModuleImages; +import mircoders.module.ModuleTopics; +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.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 org.apache.commons.net.smtp.SMTPClient; +import org.apache.commons.net.smtp.SMTPReply; +import org.apache.fop.apps.Driver; +import org.apache.fop.apps.XSLTInputHandler; +import org.apache.log.Hierarchy; +import org.apache.log.Priority; +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 freemarker.template.SimpleHash; +import freemarker.template.SimpleList; +import freemarker.template.SimpleScalar; +import freemarker.template.TemplateModelRoot; + +/* + * ServletModuleOpenIndy - + * is the open-access-servlet, which is responsible for + * adding comments to articles & + * open-postings to the newswire + * + * @author mir-coders group + * @version $Id: ServletModuleOpenIndy.java,v 1.64 2003/03/08 17:18:19 idfx Exp $ + * + */ + +public class ServletModuleOpenIndy extends ServletModule +{ + + private String commentFormTemplate, commentFormDoneTemplate, + commentFormDupeTemplate; + private String postingFormTemplate, postingFormDoneTemplate, + postingFormDupeTemplate; + private String searchResultsTemplate; + private String prepareMailTemplate,sentMailTemplate; + private ModuleContent contentModule; + private ModuleComment commentModule; + private ModuleImages imageModule; + private ModuleTopics themenModule; + private String directOp ="yes"; + private String passwdProtection ="yes"; + // Singelton / Kontruktor + private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy(); + public static ServletModule getInstance() { return instance; } + + private ServletModuleOpenIndy() { + super(); + try { + logger = new LoggerWrapper("ServletModule.OpenIndy"); + + commentFormTemplate = configuration.getString("ServletModule.OpenIndy.CommentTemplate"); + commentFormDoneTemplate = configuration.getString("ServletModule.OpenIndy.CommentDoneTemplate"); + commentFormDupeTemplate = configuration.getString("ServletModule.OpenIndy.CommentDupeTemplate"); + postingFormTemplate = configuration.getString("ServletModule.OpenIndy.PostingTemplate"); + postingFormDoneTemplate = configuration.getString("ServletModule.OpenIndy.PostingDoneTemplate"); + postingFormDupeTemplate = configuration.getString("ServletModule.OpenIndy.PostingDupeTemplate"); + searchResultsTemplate = configuration.getString("ServletModule.OpenIndy.SearchResultsTemplate"); + prepareMailTemplate = configuration.getString("ServletModule.OpenIndy.PrepareMailTemplate"); + sentMailTemplate = configuration.getString("ServletModule.OpenIndy.SentMailTemplate"); + directOp = configuration.getString("DirectOpenposting").toLowerCase(); + passwdProtection = configuration.getString("PasswdProtection").toLowerCase(); + mainModule = new ModuleComment(DatabaseComment.getInstance()); + contentModule = new ModuleContent(DatabaseContent.getInstance()); + themenModule = new ModuleTopics(DatabaseTopics.getInstance()); + imageModule = new ModuleImages(DatabaseImages.getInstance()); + defaultAction="addposting"; + + } + catch (StorageObjectFailure e) { + logger.error("servletmoduleopenindy could not be initialized: " + e.getMessage()); + } + } + + + /** + * Method for making a comment + */ + + public void addcomment(HttpServletRequest req, HttpServletResponse res) + throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure + { + String aid = req.getParameter("aid"); // the article id the comment will belong to + String language = req.getParameter("language"); + + if (aid!=null && !aid.equals("")) { + try { + SimpleHash mergeData = new SimpleHash(); + + // onetimepasswd + if (passwdProtection.equals("yes")) { + String passwd = this.createOneTimePasswd(); + HttpSession session = req.getSession(false); + session.setAttribute("passwd", passwd); + mergeData.put("passwd", passwd); + } + + if (language != null) { + HttpSession session = req.getSession(false); + session.setAttribute("Locale", new Locale(language, "")); + session.setAttribute("passwd", language); + } + + mergeData.put("aid", aid); + + SimpleHash extraInfo = new SimpleHash(); + extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData()); + + deliver(req, res, mergeData, extraInfo, commentFormTemplate); + } + catch (Throwable t) { + throw new ServletModuleFailure("ServletModuleOpenIndy.addcomment: " + t.getMessage(), t); + } + } + else throw new ServletModuleExc("aid not set!"); + } + + /** + * Method for inserting a comment into the Database and delivering + * the commentDone Page + */ + + public void inscomment(HttpServletRequest req, HttpServletResponse res) + throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure + { + String aid = req.getParameter("to_media"); // the article id the comment will belong to + if (aid!=null && !aid.equals("")) + { + // ok, collecting data from form + try { + Map withValues = getIntersectingValues(req, DatabaseComment.getInstance()); + + //no html in comments(for now) + for (Iterator i=withValues.keySet().iterator(); i.hasNext(); ){ + String k=(String)i.next(); + String v=(String)withValues.get(k); + + withValues.put(k,StringUtil.removeHTMLTags(v)); + } + withValues.put("is_published","1"); + withValues.put("to_comment_status","1"); + + //checking the onetimepasswd + if(passwdProtection.equals("yes")){ + HttpSession session = req.getSession(false); + String sessionPasswd = (String)session.getAttribute("passwd"); + if ( sessionPasswd == null){ + throw new ServletModuleUserExc("Lost password"); + } + String passwd = req.getParameter("passwd"); + if ( passwd == null || (!sessionPasswd.equals(passwd))) { + throw new ServletModuleUserExc("Missing password"); + } + session.invalidate(); + } + + // inserting into database + String id = mainModule.add(withValues); + logger.debug("id: "+id); + //insert was not successfull + if(id==null){ + deliver(req, res, new SimpleHash(), commentFormDupeTemplate); + } else { + DatabaseContent.getInstance().setUnproduced("id="+aid); + + try { + EntityComment comment = (EntityComment) DatabaseComment.getInstance().selectById(id); + MirGlobal.localizer().openPostings().afterCommentPosting(comment); + } + catch (Throwable t) { + throw new ServletModuleExc(t.getMessage()); + } + } + + // redirecting to url + // should implement back to article + SimpleHash mergeData = new SimpleHash(); + deliver(req, res, mergeData, commentFormDoneTemplate); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + else throw new ServletModuleExc("aid not set!"); + + } + + /** + * Method for delivering the form-Page for open posting + */ + + public void addposting(HttpServletRequest req, HttpServletResponse res) + throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure + { + SimpleHash mergeData = new SimpleHash(); + + // onetimepasswd + if(passwdProtection.equals("yes")){ + String passwd = this.createOneTimePasswd(); + HttpSession session = req.getSession(false); + session.setAttribute("passwd",passwd); + mergeData.put("passwd", passwd); + } + + String maxMedia = configuration.getString("ServletModule.OpenIndy.MaxMediaUploadItems"); + String defaultMedia = configuration.getString("ServletModule.OpenIndy.DefaultMediaUploadItems"); + String numOfMedia = req.getParameter("medianum"); + + if(numOfMedia==null||numOfMedia.equals("")){ + numOfMedia=defaultMedia; + } + else if(Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) { + numOfMedia = maxMedia; + } + + int mediaNum = Integer.parseInt(numOfMedia); + SimpleList mediaFields = new SimpleList(); + for(int i =0; i 0) { + try{ + DatabaseContentToTopics.getInstance().setTopics(cid,to_topicsArr); + setTopic = true; + } + catch (Exception e) { + logger.error("setting content_x_topic failed"); + contentModule.deleteById(cid); + throw new ServletModuleExc("smod - openindy :: insposting: setting content_x_topic failed: "+e.toString()); + } //end try + } //end if + + //if we're here all is ok... associate the media to the article + for(int i=0;i= totalHits) + newPosition=totalHits-1; + session.setAttribute("positionInResults",new Integer(newPosition)); + } + else { + if (searchForwardValue != null){ + int totalHits = ((Integer) session.getAttribute("numberOfHits")).intValue(); + int newPosition=((Integer)session.getAttribute("positionInResults")).intValue()+increment; + if (newPosition<0) + newPosition=0; + if (newPosition >= totalHits) + newPosition=totalHits-1; + + session.setAttribute("positionInResults",new Integer(newPosition)); + } + else { + String indexPath=configuration.getString("IndexPath"); + + + String creatorFragment = creatorTerm.makeTerm(req); + if (creatorFragment != null){ + queryString = queryString + " +" + creatorFragment; + } + + // search title, description, and content for something + // the contentTerm uses param "search_boolean" to combine its terms + String contentFragment = contentTerm.makeTerm(req); + if (contentFragment != null){ + logger.debug("contentFragment: " + contentFragment); + queryString = queryString + " +" + contentFragment; + } + + String topicFragment = topicTerm.makeTerm(req); + if (topicFragment != null){ + queryString = queryString + " +" + topicFragment; + } + + String imagesFragment = imagesTerm.makeTerm(req); + if (imagesFragment != null){ + queryString = queryString + " +" + imagesFragment; + } + + String audioFragment = audioTerm.makeTerm(req); + if (audioFragment != null){ + queryString = queryString + " +" + audioFragment; + } + + String videoFragment = videoTerm.makeTerm(req); + if (videoFragment != null){ + queryString = queryString + " +" + videoFragment; + } + + if (queryString == null || queryString == ""){ + queryString = ""; + } + else{ + try{ + Searcher searcher = null; + try { + searcher = new IndexSearcher(indexPath); + } + catch(IOException e) { + logger.debug("Can't open indexPath: " + indexPath); + throw new ServletModuleExc("Problem with Search Index! : "+ e.toString()); + } + + Query query = null; + try { + query = QueryParser.parse(queryString, "content", new StandardAnalyzer()); + } + catch(Exception e) { + searcher.close(); + logger.debug("Query don't parse: " + queryString); + throw new ServletModuleExc("Problem with Query String! (was '"+queryString+"')"); + } + + Hits hits = null; + try { + hits = searcher.search(query); + } + catch(IOException e) { + searcher.close(); + logger.debug("Can't get hits: " + e.toString()); + throw new ServletModuleExc("Problem getting hits!"); + } + + int start = 0; + int end = hits.length(); + + String sortBy=req.getParameter("search_sort"); + if (sortBy == null || sortBy.equals("")){ + throw new ServletModuleExc("Please let me sort by something!(missing search_sort)"); + } + + // here is where the documents will go for storage across sessions + ArrayList theDocumentsSorted = new ArrayList(); + + if (sortBy.equals("score")){ + for(int i = start; i < end; i++) { + theDocumentsSorted.add(hits.doc(i)); + } + } + else{ + // then we'll sort by date! + Map dateToPosition = new HashMap(end,1.0F); //we know how big it will be + for(int i = start; i < end; i++) { + String creationDate=(hits.doc(i)).get("creationDate"); + // do a little dance in case two contents created at the same second! + if (dateToPosition.containsKey(creationDate)){ + ((ArrayList) (dateToPosition.get(creationDate))).add(new Integer(i)); + } + else{ + ArrayList thePositions = new ArrayList(); + thePositions.add(new Integer(i)); + dateToPosition.put(creationDate,thePositions); + } + } + Set keys = dateToPosition.keySet(); + ArrayList keyList= new ArrayList(keys); + Collections.sort(keyList); + if (sortBy.equals("date_desc")){ + Collections.reverse(keyList); + } + else{ + if (!sortBy.equals("date_asc")){ + throw new ServletModuleExc("don't know how to sort by: "+ sortBy); + } + } + ListIterator keyTraverser = keyList.listIterator(); + while (keyTraverser.hasNext()){ + ArrayList positions = (ArrayList)dateToPosition.get((keyTraverser.next())); + ListIterator positionsTraverser=positions.listIterator(); + while (positionsTraverser.hasNext()){ + theDocumentsSorted.add(hits.doc(((Integer)(positionsTraverser.next())).intValue())); + } + } + } + + try{ + searcher.close(); + } + catch (IOException e){ + logger.debug("Can't close searcher: " + e.toString()); + throw new ServletModuleFailure("Problem closing searcher(normal):" + e.getMessage(), e); + } + + + session.removeAttribute("numberOfHits"); + session.removeAttribute("theDocumentsSorted"); + session.removeAttribute("positionInResults"); + + session.setAttribute("numberOfHits",new Integer(end)); + session.setAttribute("theDocumentsSorted",theDocumentsSorted); + session.setAttribute("positionInResults",new Integer(0)); + + } + catch (IOException e){ + logger.debug("Can't close searcher: " + e.toString()); + throw new ServletModuleFailure("Problem closing searcher: " + e.getMessage(), e); + } + } + } + } + + try { + ArrayList theDocs = (ArrayList)session.getAttribute("theDocumentsSorted"); + if (theDocs != null){ + + mergeData.put("numberOfHits", ((Integer)session.getAttribute("numberOfHits")).toString()); + SimpleList theHits = new SimpleList(); + int pIR=((Integer)session.getAttribute("positionInResults")).intValue(); + int terminus; + int numHits=((Integer)session.getAttribute("numberOfHits")).intValue(); + + if (!(pIR+increment>=numHits)){ + mergeData.put("hasNext","y"); + } + if (pIR>0){ + mergeData.put("hasPrevious","y"); + } + + if ((pIR+increment)>numHits){ + terminus=numHits; + } + else { + terminus=pIR+increment; + } + for(int i = pIR; i < terminus; i++) { + SimpleHash h = new SimpleHash(); + Document theHit = (Document)theDocs.get(i); + whereTerm.returnMeta(h,theHit); + creatorTerm.returnMeta(h,theHit); + titleTerm.returnMeta(h,theHit); + descriptionTerm.returnMeta(h,theHit); + dateTerm.returnMeta(h,theHit); + imagesTerm.returnMeta(h,theHit); + audioTerm.returnMeta(h,theHit); + videoTerm.returnMeta(h,theHit); + theHits.add(h); + } + mergeData.put("hits",theHits); + } + } + catch (Throwable e) { + logger.error("Can't iterate over hits: " + e.toString()); + + throw new ServletModuleFailure("Problem getting hits: " + e.getMessage(), e); + } + + mergeData.put("queryString",queryString); + deliver(req,res,mergeData,searchResultsTemplate); + } + catch (NullPointerException n){ + throw new ServletModuleFailure("Null Pointer: "+n.toString(), n); + } + } + + /* + * Method for dynamically generating a pdf from a fo file + */ + public void getpdf(HttpServletRequest req, HttpServletResponse res) + throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { + String ID_REQUEST_PARAM = "id"; + String language = req.getParameter("language"); + String generateFO=configuration.getString("GenerateFO"); + String generatePDF=configuration.getString("GeneratePDF"); + + + //don't do anything if we are not making FO files, or if we are + //pregenerating PDF's + if (generateFO.equals("yes") && generatePDF.equals("no")){ + //fop complains unless you do the logging this way + org.apache.log.Logger log = null; + Hierarchy hierarchy = Hierarchy.getDefaultHierarchy(); + log = hierarchy.getLoggerFor("fop"); + log.setPriority(Priority.WARN); + + String producerStorageRoot=configuration.getString("Producer.StorageRoot"); + String producerDocRoot=configuration.getString("Producer.DocRoot"); + // String templateDir=MirConfig.getPropWithHome("HTMLTemplateProcessor.Dir"); + String xslSheet=configuration.getString("Producer.HTML2FOStyleSheet"); + try { + String idParam = req.getParameter(ID_REQUEST_PARAM); + if (idParam != null) { + EntityContent contentEnt = + (EntityContent)contentModule.getById(idParam); + String publishPath = StringUtil.webdbDate2path(contentEnt.getValue("date")); + String foFile; + + if (language == null){ + foFile = producerStorageRoot + producerDocRoot + "/" + + publishPath + idParam + ".fo"; + } + else{ + foFile = producerStorageRoot + producerDocRoot + "/" + + language + publishPath + idParam + ".fo"; + } + logger.debug("USING FILES" + foFile + " and " + xslSheet); + XSLTInputHandler input = new XSLTInputHandler(new File(foFile), + new File(xslSheet)); + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + res.setContentType("application/pdf"); + + Driver driver = new Driver(); + driver.setLogger(log); + driver.setRenderer(Driver.RENDER_PDF); + driver.setOutputStream(out); + driver.render(input.getParser(), input.getInputSource()); + + byte[] content = out.toByteArray(); + res.setContentLength(content.length); + res.getOutputStream().write(content); + res.getOutputStream().flush(); + } + else { + throw new ServletModuleUserExc("Missing id parameter."); + } + } + catch (Exception ex) { + logger.error(ex.toString()); + throw new ServletModuleFailure(ex); + } + } else { + throw new ServletModuleExc("Can't generate a PDF because the config tells me not to."); + } + } + + private void _throwBadContentType (String fileName, String contentType) + throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { + + logger.error("Wrong file type uploaded!: " + fileName+" " + +contentType); + throw new ServletModuleUserExc("The file you uploaded is of the " + +"following mime-type: "+contentType + +", we do not support this mime-type. " + +"Error One or more files of unrecognized type. Sorry"); + } + + protected String createOneTimePasswd(){ + Random r = new Random(); + int random = r.nextInt(); + long l = System.currentTimeMillis(); + l = (l*l*l*l)/random; + if(l<0) l = l * -1; + String returnString = ""+l; + return returnString.substring(5); + } + + + /* this is an overwritten method of ServletModule in order + to use different bundles for open and admin */ + public void deliver(HttpServletRequest req, HttpServletResponse res, + TemplateModelRoot rtm, TemplateModelRoot popups, + String templateFilename) throws ServletModuleFailure + { + if (rtm == null) rtm = new SimpleHash(); + try { + PrintWriter out = res.getWriter(); + HTMLTemplateProcessor.process(res, templateFilename, rtm, popups, out, + getLocale(req), "bundles.open"); + out.close(); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } +} + + + diff --git a/source/mircoders/servlet/ServletModuleProducer.java b/source/mircoders/servlet/ServletModuleProducer.java index 0fe5755e..6d4be8e3 100755 --- a/source/mircoders/servlet/ServletModuleProducer.java +++ b/source/mircoders/servlet/ServletModuleProducer.java @@ -46,7 +46,6 @@ import mir.generator.Generator; import mir.log.LoggerWrapper; import mir.producer.ProducerFactory; import mir.servlet.ServletModule; -import mir.servlet.ServletModuleExc; import mir.servlet.ServletModuleFailure; import mir.util.NullWriter; import mir.util.ResourceBundleGeneratorFunction; diff --git a/source/mircoders/servlet/ServletModuleUploadedMedia.java b/source/mircoders/servlet/ServletModuleUploadedMedia.java index 2ba86132..4b168699 100755 --- a/source/mircoders/servlet/ServletModuleUploadedMedia.java +++ b/source/mircoders/servlet/ServletModuleUploadedMedia.java @@ -1,390 +1,389 @@ -/* - * 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 the com.oreilly.servlet library, 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.InputStream; -import java.net.URLEncoder; -import java.util.Map; - -import javax.servlet.ServletContext; -import javax.servlet.ServletOutputStream; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import mir.config.MirPropertiesConfiguration; -import mir.config.MirPropertiesConfiguration.PropertiesConfigExc; -import mir.entity.Entity; -import mir.entity.EntityList; -import mir.log.LoggerWrapper; -import mir.media.MediaHelper; -import mir.media.MirMedia; -import mir.misc.FileHandler; -import mir.misc.FileHandlerException; -import mir.misc.FileHandlerUserException; -import mir.misc.WebdbMultipartRequest; -import mir.module.ModuleException; -import mir.servlet.ServletModule; -import mir.servlet.ServletModuleExc; -import mir.servlet.ServletModuleUserExc; -import mir.servlet.ServletModuleFailure; -import mir.storage.StorageObjectFailure; -import mircoders.entity.EntityContent; -import mircoders.entity.EntityUploadedMedia; -import mircoders.entity.EntityUsers; -import mircoders.media.MediaRequest; -import mircoders.storage.DatabaseContent; -import mircoders.storage.DatabaseMediafolder; -import freemarker.template.SimpleHash; -import freemarker.template.SimpleList; - -/* - * ServletModuleBilder - - * liefert HTML fuer Bilder - * - * @version $Id: ServletModuleUploadedMedia.java,v 1.19 2003/03/06 05:40:40 zapata Exp $ - * @author RK, the mir-coders group - */ - -public abstract class ServletModuleUploadedMedia - extends mir.servlet.ServletModule { - - //private static DatabaseRights dbRights; - - public static ServletModule getInstance() { - return null; - } - - public ServletModuleUploadedMedia() { - super(); - logger = new LoggerWrapper("ServletModule.UploadedMedia"); - } - - public void insert(HttpServletRequest req, HttpServletResponse res) - throws ServletModuleExc, ServletModuleUserExc { - try { - EntityUsers user = _getUser(req); - MediaRequest mediaReq = new MediaRequest(user.getId(), false); - WebdbMultipartRequest mp = new WebdbMultipartRequest(req, (FileHandler)mediaReq); - EntityList mediaList = mediaReq.getEntityList(); - String articleid = (String) mp.getParameters().get("articleid"); - - if (articleid!=null) { - EntityContent entContent = (EntityContent) DatabaseContent.getInstance().selectById(articleid); - - mediaList.rewind(); - - while (mediaList.hasNext()) { - entContent.attach( ( (EntityUploadedMedia) mediaList.next()).getId()); - } - mediaList.rewind(); - - ((ServletModuleContent) ServletModuleContent.getInstance())._showObject(articleid, req, res); - - return; - } - - SimpleHash mergeData = new SimpleHash(); - SimpleHash popups = new SimpleHash(); - mergeData.put("contentlist", mediaList); - if (mediaList.getOrder() != null) { - mergeData.put("order", mediaList.getOrder()); - mergeData.put("order_encoded", URLEncoder.encode(mediaList.getOrder())); - } - mergeData.put("count", (new Integer(mediaList.getCount())).toString()); - mergeData.put("from", (new Integer(mediaList.getFrom())).toString()); - mergeData.put("to", (new Integer(mediaList.getTo())).toString()); - if (mediaList.hasNextBatch()) - mergeData.put("next", (new Integer(mediaList.getNextBatch())).toString()); - if (mediaList.hasPrevBatch()) - mergeData.put("prev", (new Integer(mediaList.getPrevBatch())).toString()); - //fetch the popups - popups.put("mediafolderPopupData", DatabaseMediafolder.getInstance().getPopupData()); - // raus damit - deliver(req, res, mergeData, popups, templateListString); - } - catch (FileHandlerUserException e) { - logger.error("ServletModuleUploadedMedia.insert: " + e.getMessage()); - throw new ServletModuleUserExc(e.getMessage()); - } - catch (FileHandlerException e) { - throw new ServletModuleFailure("upload -- media handling exception " + e.toString(), e); - } - catch (StorageObjectFailure e) { - throw new ServletModuleFailure("upload -- storageobjectexception " + e.toString(), e); - } - catch (IOException e) { - throw new ServletModuleFailure("upload -- ioexception " + e.toString(), e); - } - catch (PropertiesConfigExc e) { - throw new ServletModuleFailure("upload -- configexception " + e.toString(), e); - } - catch (Throwable t) { - throw new ServletModuleFailure("upload -- exception " + t.toString(), t); - } - } - - public void update(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc { - - try { - EntityUsers user = _getUser(req); - WebdbMultipartRequest mp = new WebdbMultipartRequest(req, null); - Map parameters = mp.getParameters(); - - parameters.put("to_publisher", user.getId()); - parameters.put("is_produced", "0"); - if (!parameters.containsKey("is_published")) - parameters.put("is_published", "0"); - - String id = mainModule.set(parameters); - logger.debug("update: media ID = " + id); - _edit(id, req, res); - } - catch (Throwable e) { - throw new ServletModuleFailure("upload -- exception " + e.toString(), e); - } - - } - - - public void list(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc { - // Parameter auswerten - SimpleHash mergeData = new SimpleHash(); - SimpleHash popups = new SimpleHash(); - - String query_text = req.getParameter("query_text"); - mergeData.put("query_text", query_text); - if (query_text != null) mergeData.put("query_text_encoded", URLEncoder.encode(query_text)); - String query_field = req.getParameter("query_field"); - mergeData.put("query_field", query_field); - String query_is_published = req.getParameter("query_is_published"); - mergeData.put("query_is_published", query_is_published); - String query_media_folder = req.getParameter("query_media_folder"); - mergeData.put("query_media_folder", query_media_folder); - String offset = req.getParameter("offset"); - if (offset == null || offset.equals("")) offset = "0"; - mergeData.put("offset", offset); - - String order = req.getParameter("order"); - if (order == null || order.equals("")) order = "webdb_lastchange desc"; - - // if in connection mode to content - String cid = req.getParameter("cid"); - mergeData.put("cid", cid); - - - // sql basteln - String whereClause = ""; - boolean isFirst = true; - if (query_text != null && !query_text.equalsIgnoreCase("")) { - whereClause += "lower(" + query_field + ") like lower('%" + query_text + "%')"; - isFirst = false; - } - if (query_is_published != null && !query_is_published.equals("")) { - if (isFirst == false) whereClause += " and "; - whereClause += "is_published='" + query_is_published + "'"; - isFirst = false; - } - if (query_media_folder != null && !query_media_folder.equals("")) { - if (isFirst == false) whereClause += " and "; - whereClause += "to_media_folder='" + query_media_folder + "'"; - } - //theLog.printDebugInfo("sql-whereclause: " + whereClause + " order: " + order + " offset: " + offset); - - // fetch and deliver - try { - if (query_text != null || query_is_published != null || query_media_folder != null) { - EntityList theList = mainModule.getByWhereClause(whereClause, order, (new Integer(offset)).intValue(), 10); - if (theList != null) { - mergeData.put("contentlist", theList); - if (theList.getOrder() != null) { - mergeData.put("order", theList.getOrder()); - mergeData.put("order_encoded", URLEncoder.encode(theList.getOrder())); - } - mergeData.put("count", (new Integer(theList.getCount())).toString()); - mergeData.put("from", (new Integer(theList.getFrom())).toString()); - mergeData.put("to", (new Integer(theList.getTo())).toString()); - if (theList.hasNextBatch()) - mergeData.put("next", (new Integer(theList.getNextBatch())).toString()); - if (theList.hasPrevBatch()) - mergeData.put("prev", (new Integer(theList.getPrevBatch())).toString()); - } - } - popups.put("mediafolderPopupData", DatabaseMediafolder.getInstance().getPopupData()); - - deliver(req, res, mergeData, popups, templateListString); - } - catch (Throwable e) { - throw new ServletModuleFailure(e); - } - } - - - public void add(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc { - try { - SimpleHash mergeData = new SimpleHash(); - SimpleHash popups = new SimpleHash(); - String maxMedia = MirPropertiesConfiguration.instance().getString("ServletModule.OpenIndy.MaxMediaUploadItems"); - String numOfMedia = req.getParameter("medianum"); - - mergeData.put("new", "1"); - mergeData.put("articleid", req.getParameter("articleid")); - - popups.put("mediafolderPopupData", DatabaseMediafolder.getInstance().getPopupData()); - - if (numOfMedia==null || numOfMedia.equals("")) { - numOfMedia="1"; - } - else if(Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) { - numOfMedia = maxMedia; - } - - int mediaNum = Integer.parseInt(numOfMedia); - SimpleList mediaFields = new SimpleList(); - for(int i =0; i Integer.parseInt(maxMedia)) { + numOfMedia = maxMedia; + } + + int mediaNum = Integer.parseInt(numOfMedia); + SimpleList mediaFields = new SimpleList(); + for(int i =0; i 0) || - (aRequestParser.getParameter("newpassword2") != null && - aRequestParser.getParameter("newpassword2").length() > 0) - ) { - String newPassword = aRequestParser.getParameterWithDefault("newpassword", ""); - String newPassword2 = aRequestParser.getParameterWithDefault("newpassword2", ""); - - if (newPassword.length() == 0 || newPassword2.length() == 0) { - throw new ServletModuleUserExc("The new password must be entered twice!"); - } - - if (!newPassword.equals(newPassword2)) { - throw new ServletModuleUserExc("New password differes from confirmation"); - } - - return newPassword; - } - else - return null; - } - - public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse) - throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure - { - try { - HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); - Map withValues = getIntersectingValues(aRequest, mainModule.getStorageObject()); - - String newPassword=checkPassword(requestParser); - if (newPassword!=null) - withValues.put("password", newPassword); - else - throw new ServletModuleUserExc("Password is empty"); - - 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); - - Map withValues = getIntersectingValues(aRequest, mainModule.getStorageObject()); - - String newPassword=checkPassword(requestParser); - if (newPassword!=null) - withValues.put("password", newPassword); - - mainModule.set(withValues); - - if (requestParser.hasParameter("returnurl")) - redirect(aResponse, requestParser.getParameter("returnurl")); - else - list(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 the com.oreilly.servlet library, 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.ServletModuleExc; +import mir.servlet.ServletModuleFailure; +import mir.servlet.ServletModuleUserExc; +import mir.storage.StorageObjectFailure; +import mir.util.HTTPRequestParser; +import mircoders.module.ModuleUsers; +import mircoders.storage.DatabaseUsers; +import freemarker.template.SimpleHash; + +/* + * ServletModuleUsers - + * liefert HTML fuer Users + * + * + * @author RK + */ + +public class ServletModuleUsers extends ServletModule +{ + private static ServletModuleUsers instance = new ServletModuleUsers(); + public static ServletModule getInstance() { return instance; } + + private ServletModuleUsers() { + super(); + logger = new LoggerWrapper("ServletModule.Users"); + + templateListString = configuration.getString("ServletModule.Users.ListTemplate"); + templateObjektString = configuration.getString("ServletModule.Users.ObjektTemplate"); + templateConfirmString = configuration.getString("ServletModule.Users.ConfirmTemplate"); + + try { + mainModule = new ModuleUsers(DatabaseUsers.getInstance()); + } + catch (StorageObjectFailure e) { + logger.debug("initialization of ServletModuleUsers failed!: " + e.getMessage()); + } + } + + public void edit(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc + { + String idParam = req.getParameter("id"); + + if (idParam == null) + throw new ServletModuleExc("ServletModuleUser.edit: invalid call: (id) not specified"); + + try { + deliver(req, res, mainModule.getById(idParam), templateObjektString); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + public void add(HttpServletRequest req, HttpServletResponse res) + throws ServletModuleExc + { + try { + SimpleHash mergeData = new SimpleHash(); + mergeData.put("new", "1"); + deliver(req, res, mergeData, templateObjektString); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + public String checkPassword(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", ""); + + if (newPassword.length() == 0 || newPassword2.length() == 0) { + throw new ServletModuleUserExc("The new password must be entered twice!"); + } + + if (!newPassword.equals(newPassword2)) { + throw new ServletModuleUserExc("New password differes from confirmation"); + } + + return newPassword; + } + else + return null; + } + + public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse) + throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure + { + try { + HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); + Map withValues = getIntersectingValues(aRequest, mainModule.getStorageObject()); + + String newPassword=checkPassword(requestParser); + if (newPassword!=null) + withValues.put("password", newPassword); + else + throw new ServletModuleUserExc("Password is empty"); + + 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); + + Map withValues = getIntersectingValues(aRequest, mainModule.getStorageObject()); + + String newPassword=checkPassword(requestParser); + if (newPassword!=null) + withValues.put("password", newPassword); + + mainModule.set(withValues); + + if (requestParser.hasParameter("returnurl")) + redirect(aResponse, requestParser.getParameter("returnurl")); + else + list(aRequest, aResponse); + } + catch (Throwable e) { + throw new ServletModuleFailure(e); + } + } + + +} -- 2.11.0