AdministrationServlet.java :  » Wiki-Engine » VeryQuickWiki » vqwiki » servlets » Java Open Source

Java Open Source » Wiki Engine » VeryQuickWiki 
VeryQuickWiki » vqwiki » servlets » AdministrationServlet.java
/*
 * Copyright 2002 Gareth Cronin
 * This software is subject to the GNU Lesser General Public Licence (LGPL)
 */
package vqwiki.servlets;

import org.apache.log4j.Logger;

import vqwiki.ChangeLog;
import vqwiki.Environment;
import vqwiki.Topic;
import vqwiki.WikiBase;
import vqwiki.WikiMembers;
import vqwiki.db.DBDate;
import vqwiki.utils.JSPUtils;
import vqwiki.utils.Utilities;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Collection;
import java.util.Iterator;
import java.util.ResourceBundle;

public class AdministrationServlet extends VQWikiServlet {

    private static final Logger logger = Logger.getLogger(AdministrationServlet.class);
    private Environment environment = Environment.getInstance();

    /**
     *
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse httpServletResponse) throws ServletException,
        IOException {
        if (!Utilities.isAdmin(request)) {
            request.setAttribute("title", Utilities.resource("login.title", request.getLocale()));
            logger.debug("Current URL: " + request.getRequestURL());
            String rootPath = JSPUtils.createLocalRootPath(request, (String) request.getAttribute("virtualWiki"));
            StringBuffer buffer = new StringBuffer();
            buffer.append(rootPath);
            buffer.append("Wiki?action=" + WikiServlet.ACTION_ADMIN + "&username=admin");
            request.setAttribute("redirect", buffer.toString());
            dispatch("/jsp/login.jsp", request, httpServletResponse);
            return;
        }
        if (request.getParameter("function") != null) {
            if (request.getParameter("function").equals("logout")) {
                request.getSession().removeAttribute("admin");
                redirect(
                    JSPUtils.createRedirectURL(request, "Wiki?StartingPoints"),
                    httpServletResponse
                );
                return;
            }
        }
        dispatch("/jsp/admin.jsp", request, httpServletResponse);
    }

    /**
     *
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        logger.debug("Admin request");
        String message = "";
        try {
            ResourceBundle messages = ResourceBundle.getBundle("ApplicationResources", request.getLocale());
            String virtualWiki = (String) request.getAttribute("virtual-wiki");
            String functionType = request.getParameter("function");
            if (request.getParameter("function") == null) {
                // nothing
            } else if (functionType.equals("refreshIndex")) {
                WikiBase.getInstance().getSearchEngineInstance().refreshIndex();
                message = messages.getString("admin.message.indexrefreshed");
            } else if (request.getParameter("function").equals("logout")) {
                request.getSession().removeAttribute("admin");
                redirect("Wiki?StartingPoints", response);
                return;
            } else if (functionType.equals("purge")) {
                Collection purged = WikiBase.getInstance().purgeDeletes(request.getParameter("virtual-wiki"));
                StringBuffer buffer = new StringBuffer();
                ChangeLog cl = WikiBase.getInstance().getChangeLogInstance();
                cl.removeChanges(virtualWiki, purged);
                buffer.append("Purged: ");
                for (Iterator iterator = purged.iterator(); iterator.hasNext();) {
                    String topicName = (String) iterator.next();
                    buffer.append(topicName);
                    buffer.append("; ");
                }
                message = buffer.toString();
            } else if (functionType.equals("purge-versions")) {
                DateFormat dateFormat = DateFormat.getInstance();
                DBDate date = new DBDate(dateFormat.parse(request.getParameter("purgedate")));
                WikiBase.getInstance().purgeVersionsOlderThan(virtualWiki, date);
            } else if (functionType.equals("properties")) {
                Environment en = environment;
                en.setEncodePasswords(request.getParameter(Environment.PROPERTY_ENCODE_PASSWORDS) != null);
                en.setEditTimeOut(Integer.parseInt(request.getParameter("editTimeout")));
                en.setSetting(Environment.PROPERTY_RECENT_CHANGES_DAYS, request.getParameter("recentChangesDays"));
                en.setSetting(Environment.PROPERTY_MAXIMUM_BACKLINKS, request.getParameter("maximumBacklinks"));
                en.setIndexRefreshInterval(Integer.parseInt(request.getParameter("indexInterval")));
                en.setRecentChangesRefreshInterval(Integer.parseInt(request.getParameter("recentChangesInterval")));
                en.setSetting(Environment.PROPERTY_SMTP_HOST, request.getParameter("smtp"));
                en.setSetting(Environment.PROPERTY_SMTP_USERNAME, request.getParameter("smtpUsername"));
                en.setSmtpPassword(request.getParameter("smtpPassword"));
                en.setSetting(Environment.PROPERTY_REPLY_ADDRESS, request.getParameter("replyAddress"));
                en.setSetting(Environment.PROPERTY_NEW_LINE_BREAKS, request.getParameter("newLineBreaks"));
                en.setVersioningOn(request.getParameter("versioning") != null);
                en.setAllowHTML(request.getParameter("allowHtml") != null);
                en.setForceUsername(request.getParameter("forceUserName") != null);
                en.setAllowBackTick(request.getParameter("allowBackTick") != null);
                en.setSetting(
                    Environment.PROPERTY_ALLOW_VWIKI_LIST,
                    request.getParameter("allowVirtualWikiList") != null
                );
                en.setSetting(
                    Environment.PROPERTY_ATTACHMENT_INDEXING_ENABLED,
                    request.getParameter("indexAttachments") != null
                );
                en.setSetting(
                    Environment.PROPERTY_EXTLINKS_INDEXING_ENABLED,
                    request.getParameter("indexExtLinks") != null
                );
                en.setSetting(
                    Environment.PROPERTY_ATTACHMENT_TIMESTAMP,
                    request.getParameter("attachmentTimestamp") != null
                );
                en.setSetting(
                    Environment.PROPERTY_FRANZ_NEWTOPIC_STYLE,
                    request.getParameter("franzNewTopicStyle") != null
                );
                en.setUploadDir(request.getParameter("uploadDir"));
                en.setHomeDir(request.getParameter("homeDir"));
                en.setPersistenceType(Integer.parseInt(request.getParameter("persistenceType")));
                if (request.getParameter("driver") != null) {
                    en.setDriver(request.getParameter("driver"));
                    en.setUrl(request.getParameter("url"));
                    en.setUserName(request.getParameter("dbUsername"));
                    en.setPassword(request.getParameter("dbPassword"));
                    en.setSetting(
                        Environment.PROPERTY_DBCP_MAX_ACTIVE, Integer.parseInt(request.getParameter("dbcp_max_active"))
                    );
                    en.setSetting(Environment.PROPERTY_DBCP_MAX_IDLE, Integer.parseInt(request.getParameter("dbcp_max_idle")));
                    en.setSetting(Environment.PROPERTY_DBCP_TEST_ON_BORROW, request.getParameter("dbcp_test_on_borrow") != null);
                    en.setSetting(Environment.PROPERTY_DBCP_TEST_ON_RETURN, request.getParameter("dbcp_test_on_return") != null);
                    en.setSetting(
                        Environment.PROPERTY_DBCP_TEST_WHILE_IDLE, request.getParameter("dbcp_test_while_idle") != null
                    );
                    en.setSetting(
                        Environment.PROPERTY_DBCP_MIN_EVICTABLE_IDLE_TIME,
                        Integer.parseInt(request.getParameter("dbcp_min_evictable_idle_time"))
                    );
                    en.setSetting(
                        Environment.PROPERTY_DBCP_TIME_BETWEEN_EVICTION_RUNS,
                        Integer.parseInt(request.getParameter("dbcp_time_between_eviction_runs"))
                    );
                    en.setSetting(
                        Environment.PROPERTY_DBCP_NUM_TESTS_PER_EVICTION_RUN,
                        Integer.parseInt(request.getParameter("dbcp_num_tests_per_eviction_run"))
                    );
                    en.setSetting(
                        Environment.PROPERTY_DBCP_WHEN_EXHAUSTED_ACTION,
                        Integer.parseInt(request.getParameter("dbcp_when_exhausted_action"))
                    );
                    en.setSetting(Environment.PROPERTY_DBCP_VALIDATION_QUERY, request.getParameter("dbcp_validation_query"));
                    en.setSetting(
                        Environment.PROPERTY_DBCP_REMOVE_ABANDONED, request.getParameter("dbcp_remove_abandoned") != null
                    );
                    en.setSetting(
                        Environment.PROPERTY_DBCP_REMOVE_ABANDONED_TIMEOUT,
                        Integer.parseInt(request.getParameter("dbcp_remove_abandoned_timeout"))
                    );
                    en.setSetting(Environment.PROPERTY_DBCP_LOG_ABANDONED, request.getParameter("dbcp_log_abandoned") != null);
                }
                en.setSetting(
                    Environment.PROPERTY_ALLOW_TEMPLATES,
                    request.getParameter("allowTemplates") != null
                );
                en.setSetting(
                    Environment.PROPERTY_USE_PREVIEW,
                    request.getParameter("usePreview") != null
                );
                en.setSetting(Environment.PROPERTY_DEFAULT_TOPIC, request.getParameter("defaultTopic"));
                en.setSetting(Environment.PROPERTY_PARSER, request.getParameter(Environment.PROPERTY_PARSER));
                en.setSetting(Environment.PROPERTY_FORMAT_LEXER, request.getParameter("formatLexer"));
                en.setSetting(Environment.PROPERTY_LINK_LEXER, request.getParameter("linkLexer"));
                en.setSetting(Environment.PROPERTY_LAYOUT_LEXER, request.getParameter("layoutLexer"));
                int maxFileSizeInKB = Integer.parseInt(request.getParameter("maximumFileSize"));
                en.setSetting(Environment.PROPERTY_MAX_FILE_SIZE, maxFileSizeInKB * 1000);
                en.setSetting(Environment.PROPERTY_ATTACHMENT_TYPE, request.getParameter("attachmentType"));
                en.setSetting(Environment.PROPERTY_CONVERT_TABS, (request.getParameter("convertTabs") != null));
                en.setSetting(Environment.PROPERTY_CONVERT_ENTITIES, (request.getParameter("convertEntities") != null));
                if (request.getParameter("databaseType") != null) {
                    en.setSetting(Environment.PROPERTY_DATABASE_TYPE, request.getParameter("databaseType"));
                }
                if (request.getParameter("wikiServerHostname") !=  null && !request.getParameter("wikiServerHostname").equals("")) {
                    en.setSetting(Environment.PROPERTY_WIKI_SERVER_HOSTNAME, request.getParameter("wikiServerHostname"));
                } else {
                    en.setSetting(Environment.PROPERTY_WIKI_SERVER_HOSTNAME,"");
                }
                en.setSetting(Environment.PROPERTY_FILE_ENCODING, request.getParameter("fileEncoding"));
                en.setSetting(
                    Environment.PROPERTY_SEPARATE_WIKI_TITLE_WORDS,
                    request.getParameter("separateWikiTitleWords") != null
                );
                en.setSetting(
                    Environment.PROPERTY_SUPPRESS_NOTIFY_WITHIN_SAME_DAY,
                    request.getParameter("suppressNotifyWithinSameDay") != null
                );
                en.setUsergroupType(Integer.parseInt(request.getParameter("usergroupType")));
                String[] autoFill = {
                    Environment.PROPERTY_USERGROUP_FACTORY,
                    Environment.PROPERTY_USERGROUP_URL,
                    Environment.PROPERTY_USERGROUP_USERNAME,
                    Environment.PROPERTY_USERGROUP_PASSWORD,
                    Environment.PROPERTY_USERGROUP_BASIC_SEARCH,
                    Environment.PROPERTY_USERGROUP_SEARCH_RESTRICTIONS,
                    Environment.PROPERTY_USERGROUP_USERID_FIELD,
                    Environment.PROPERTY_USERGROUP_FULLNAME_FIELD,
                    Environment.PROPERTY_USERGROUP_MAIL_FIELD,
                    Environment.PROPERTY_USERGROUP_DETAILVIEW
                };
                for (int i = 0; i < autoFill.length; i++) {
                    if (request.getParameter(autoFill[i]) != null) {
                        if (autoFill[i].equals(Environment.PROPERTY_USERGROUP_PASSWORD)) {
                            en.setUserGroupPassword(request.getParameter(autoFill[i]));
                        } else {
                            en.setSetting(autoFill[i], request.getParameter(autoFill[i]));
                        }
                    }
                }
                // FIXME (PARSER_TEMP) - temporary property until conversion is complete
                en.setUseNewParser(request.getParameter(Environment.PROPERTY_USE_NEW_PARSER) != null);
                en.saveProperties();
                en.refresh();
                WikiBase.initialise();
                message = messages.getString("admin.message.changessaved");
            } else if (functionType.equals("clearEditLock")) {
                WikiBase base = WikiBase.getInstance();
                base.unlockTopic(request.getParameter("virtual-wiki"), request.getParameter("topic"));
                message = Utilities.resource("admin.message.lockcleared", request.getLocale());
            } else if (functionType.equals("removeUser")) {
                String user = request.getParameter("userName");
                WikiMembers members = WikiBase.getInstance().getWikiMembersInstance(virtualWiki);
                if (members.removeMember(user)) {
                    message = user + messages.getString("admin.message.userremoved.success");
                } else {
                    message = user + messages.getString("admin.message.userremoved.failure");
                }
            } else if (functionType.equals("addVirtualWiki")) {
                String newWiki = request.getParameter("newVirtualWiki");
                logger.debug("Adding new Wiki: " + newWiki);
                WikiBase.getInstance().addVirtualWiki(newWiki);
                message = messages.getString("admin.message.virtualwikiadded");
                WikiBase.initialise();
            } else if (functionType.equals("changePassword")) {
                String oldPassword = request.getParameter("oldPassword");
                String newPassword = request.getParameter("newPassword");
                String confirmPassword = request.getParameter("confirmPassword");
                if (!environment.getAdminPassword().equals(oldPassword)) {
                    message = messages.getString("admin.message.oldpasswordincorrect");
                } else if (!newPassword.equals(confirmPassword)) {
                    message = messages.getString("admin.message.passwordsnomatch");
                } else {
                    environment.setAdminPassword(newPassword);
                    environment.saveProperties();
                    message = messages.getString("admin.message.passwordchanged");
                }
            } else if ("panic".equals(functionType)) {
                WikiBase.getInstance().panic();
            }
        } catch (Exception err) {
            if (err instanceof java.sql.SQLException) {
                logger.warn("SQL-Exception in the admin console catched", err);
                message = err.getMessage();
            } else {
                error(request, response, err);
                return;
            }
        }
        try {
            String virtualWiki = (String) request.getAttribute("virtualWiki");
            if (request.getParameter("addReadOnly") != null) {
                Topic t = new Topic(request.getParameter("readOnlyTopic"));
                t.makeTopicReadOnly(virtualWiki);
            }
            if (request.getParameter("removeReadOnly") != null) {
                String[] topics = request.getParameterValues("markRemove");
                for (int i = 0; i < topics.length; i++) {
                    Topic t = new Topic(topics[i]);
                    t.makeTopicWritable(virtualWiki);
                }
            }
        } catch (Exception e) {
            logger.error("", e);
        }
        String next = JSPUtils.createRedirectURL(request, "Wiki?action=" + WikiServlet.ACTION_ADMIN + "&message=" + message);
        response.sendRedirect(response.encodeRedirectURL(next));
    }
}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.