KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > snipsnap > net > admin > ConfigureServlet


1 /*
2  * This file is part of "SnipSnap Wiki/Weblog".
3  *
4  * Copyright (c) 2002 Stephan J. Schmidt, Matthias L. Jugel
5  * All Rights Reserved.
6  *
7  * Please visit http://snipsnap.org/ for updates and contact.
8  *
9  * --LICENSE NOTICE--
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23  * --LICENSE NOTICE--
24  */

25 package org.snipsnap.net.admin;
26
27 import org.radeox.util.logging.Logger;
28 import org.snipsnap.app.Application;
29 import org.snipsnap.app.ApplicationManager;
30 import org.snipsnap.config.Configuration;
31 import org.snipsnap.config.ConfigurationManager;
32 import org.snipsnap.config.ConfigurationProxy;
33 import org.snipsnap.config.InitializeDatabase;
34 import org.snipsnap.container.Components;
35 import org.snipsnap.net.filter.MultipartWrapper;
36 import org.snipsnap.snip.Snip;
37 import org.snipsnap.snip.SnipSpace;
38 import org.snipsnap.user.User;
39
40 import javax.servlet.RequestDispatcher JavaDoc;
41 import javax.servlet.ServletException JavaDoc;
42 import javax.servlet.http.HttpServlet JavaDoc;
43 import javax.servlet.http.HttpServletRequest JavaDoc;
44 import javax.servlet.http.HttpServletResponse JavaDoc;
45 import javax.servlet.http.HttpSession JavaDoc;
46 import java.io.ByteArrayOutputStream JavaDoc;
47 import java.io.File JavaDoc;
48 import java.io.FileOutputStream JavaDoc;
49 import java.io.IOException JavaDoc;
50 import java.io.OutputStreamWriter JavaDoc;
51 import java.net.URL JavaDoc;
52 import java.util.ArrayList JavaDoc;
53 import java.util.Arrays JavaDoc;
54 import java.util.HashMap JavaDoc;
55 import java.util.Iterator JavaDoc;
56 import java.util.List JavaDoc;
57 import java.util.Locale JavaDoc;
58 import java.util.Map JavaDoc;
59 import java.util.TimeZone JavaDoc;
60
61 /**
62  * @author Matthias L. Jugel
63  * @version $Id: ConfigureServlet.java 1736 2004-09-03 14:11:34Z leo $
64  */

65 public class ConfigureServlet extends HttpServlet JavaDoc {
66
67   protected final static String JavaDoc ATT_PREFIX = "prefix";
68   protected final static String JavaDoc ATT_KEY = "key";
69   protected final static String JavaDoc ATT_APPLICATION = "app";
70   protected final static String JavaDoc ATT_CONFIG = "newconfig";
71   protected final static String JavaDoc ATT_GLOBAL_CONFIG = "global";
72   protected final static String JavaDoc ATT_VALIDATOR = "validator";
73   protected final static String JavaDoc ATT_ADVANCED = "advanced";
74   protected final static String JavaDoc ATT_DEFAULTS = "defaults";
75   protected final static String JavaDoc ATT_USAGE = "usage";
76   protected final static String JavaDoc ATT_FINISH = "finish";
77   protected final static String JavaDoc ATT_STEPS = "steps";
78   protected final static String JavaDoc ATT_STEP = "step";
79   protected final static String JavaDoc ATT_ERRORS = "errors";
80   protected final static String JavaDoc ATT_USER = "configuser";
81
82   protected final static String JavaDoc STEP_LOGIN = "login";
83
84   protected final static String JavaDoc STEP_APPLICATION = "application";
85   protected final static String JavaDoc STEP_THEME = "theme";
86   protected final static String JavaDoc STEP_ADMINISTRATOR = "administrator";
87   protected final static String JavaDoc STEP_LOCALIZATION = "localization";
88   protected final static String JavaDoc STEP_PERMISSIONS = "permissions";
89   protected final static String JavaDoc STEP_MAIL = "mail";
90   protected final static String JavaDoc STEP_MOBLOG = "moblog";
91   protected final static String JavaDoc STEP_PROXY = "proxy";
92   protected final static String JavaDoc STEP_DATABASE = "database";
93   protected final static String JavaDoc STEP_EXPERT = "expert";
94   protected final static String JavaDoc STEP_FINISH = "finish";
95
96   protected final static String JavaDoc STEP_IMPORT = "import";
97   protected final static String JavaDoc STEP_EXPORT = "export";
98   protected final static String JavaDoc STEP_USERS = "users";
99   protected final static String JavaDoc STEP_SEARCH = "search";
100   protected final static String JavaDoc STEP_MAINTENANCE = "maintenance";
101
102   private final static List JavaDoc LOGIN_STEPS = Arrays.asList(new String JavaDoc[]{
103     STEP_LOGIN
104   });
105
106   private final static List JavaDoc BASIC_STEPS = Arrays.asList(new String JavaDoc[]{
107     STEP_ADMINISTRATOR,
108     STEP_APPLICATION,
109     STEP_FINISH,
110   });
111
112   private final static List JavaDoc EXPERT_STEPS = Arrays.asList(new String JavaDoc[]{
113     STEP_THEME,
114     STEP_LOCALIZATION,
115     STEP_PERMISSIONS,
116     STEP_MAIL,
117     STEP_MOBLOG,
118     STEP_PROXY,
119     STEP_EXPERT,
120   });
121
122   private final static List JavaDoc CONFIG_STEPS = Arrays.asList(new String JavaDoc[]{
123     STEP_USERS,
124     STEP_IMPORT,
125     STEP_EXPORT,
126     STEP_SEARCH,
127     STEP_MAINTENANCE
128   });
129
130   private final static List JavaDoc HANDLERS = Arrays.asList(new String JavaDoc[]{
131     "org.snipsnap.net.admin.Maintenance",
132     "org.snipsnap.net.admin.DatabaseExport",
133     "org.snipsnap.net.admin.DatabaseImport",
134     "org.snipsnap.net.admin.ManageSearchEngine",
135     "org.snipsnap.net.admin.ManageUsers",
136     "org.snipsnap.net.admin.SetupAdministrator",
137     "org.snipsnap.net.admin.SetupApplication",
138     "org.snipsnap.net.admin.SetupDatabase",
139     "org.snipsnap.net.admin.SetupExpert",
140     "org.snipsnap.net.admin.SetupLocalization",
141     "org.snipsnap.net.admin.SetupMail",
142     "org.snipsnap.net.admin.SetupMoblog",
143     "org.snipsnap.net.admin.SetupPermissions",
144     "org.snipsnap.net.admin.SetupProxy",
145     "org.snipsnap.net.admin.SetupTheme"
146   });
147
148   Map JavaDoc handlers = new HashMap JavaDoc();
149
150   public void init() throws ServletException JavaDoc {
151     super.init();
152     Iterator JavaDoc handlerIt = HANDLERS.iterator();
153     while (handlerIt.hasNext()) {
154       String JavaDoc className = (String JavaDoc) handlerIt.next();
155       try {
156         SetupHandler handler = (SetupHandler) Class.forName(className).newInstance();
157         String JavaDoc handlerName = handler.getName();
158         handlers.put(handlerName, handler);
159         System.err.println("ConfigureServlet: added setup handler: " + handlerName);
160       } catch (Exception JavaDoc e) {
161         System.err.println("ConfigureServlet: unable to instantiate setup handler: " + e);
162         e.printStackTrace();
163       }
164     }
165   }
166
167   protected void doPost(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws ServletException JavaDoc, IOException JavaDoc {
168     doGet(request, response);
169   }
170
171   public void doGet(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
172           throws ServletException JavaDoc, IOException JavaDoc {
173
174     // If this is not a multipart/form-data request continue
175
String JavaDoc type = request.getHeader("Content-Type");
176     if (type != null && type.startsWith("multipart/form-data")) {
177       try {
178         request = new MultipartWrapper(request, "UTF-8");
179       } catch (IllegalArgumentException JavaDoc e) {
180         Logger.warn("ConfigureServlet: multipart/form-data wrapper:" + e.getMessage());
181       }
182     }
183
184     HttpSession JavaDoc session = request.getSession();
185     Configuration config = (Configuration) session.getAttribute(ATT_CONFIG);
186
187     String JavaDoc prefix = request.getParameter(ATT_PREFIX);
188     if (null == prefix) {
189       prefix = (String JavaDoc) request.getAttribute(Configuration.APP_PREFIX);
190     }
191     if (prefix != null && config != null && !prefix.equals(config.getPrefix())) {
192       session.removeAttribute(ATT_CONFIG);
193       config = null;
194     }
195
196     ApplicationManager appManager = null;
197     String JavaDoc appOid = null;
198     if (config == null && ConfigurationProxy.getInstance().isInstalled()) {
199       appManager = (ApplicationManager) Components.getComponent(ApplicationManager.class);
200       appOid = appManager.getApplication(prefix != null && !"".equals(prefix) ? prefix : "/");
201       Configuration existingConfig = ConfigurationManager.getInstance().getConfiguration(appOid);
202       session.removeAttribute(ATT_USER);
203       session.removeAttribute(ATT_STEP);
204       session.removeAttribute(ATT_STEPS);
205       if (existingConfig != null) {
206         // make a copy and work on it as long as we are changing
207
config = ConfigurationProxy.newInstance(existingConfig);
208       }
209     }
210
211     if (null == config) {
212       config = ConfigurationProxy.newInstance();
213       if (prefix != null && !"".equals(prefix)) {
214         if (!prefix.startsWith("/")) {
215           prefix = "/" + prefix;
216         }
217         config.setPrefix(prefix);
218       }
219     }
220
221     request.setAttribute(ATT_PREFIX, prefix);
222
223     // TODO same as in InitFilter
224
Application app = Application.get();
225     String JavaDoc xForwardedHost = request.getHeader("X-Forwarded-Host");
226     if (xForwardedHost != null) {
227       String JavaDoc protocol = config.get(Configuration.APP_REAL_PROTOCOL, "http");
228       String JavaDoc contextPath = config.get(Configuration.APP_REAL_PATH, "");
229
230       int colonIndex = xForwardedHost.indexOf(':');
231       String JavaDoc host = xForwardedHost;
232       if (colonIndex != -1) {
233         host = host.substring(0, colonIndex);
234         int port = Integer.parseInt(xForwardedHost.substring(colonIndex + 1));
235         app.storeObject(Application.URL, new URL JavaDoc(protocol, host, port, contextPath));
236       } else {
237         app.storeObject(Application.URL, new URL JavaDoc(protocol, host, contextPath));
238       }
239     } else {
240       String JavaDoc protocol = new URL JavaDoc(request.getRequestURL().toString()).getProtocol();
241       String JavaDoc host = request.getServerName();
242       int port = request.getServerPort();
243       String JavaDoc contextPath = request.getContextPath() + ("/".equals(prefix) ? "" : prefix);
244
245       app.storeObject(Application.URL, new URL JavaDoc(protocol, host, port, contextPath));
246     }
247
248     Application.get().setConfiguration(config);
249     session.setAttribute(ATT_CONFIG, config);
250
251 // if (config.allow(Configuration.APP_PERM_REGISTER) &&
252
// config.allow(Configuration.APP_PERM_WEBLOGSPING)) {
253
// session.setAttribute(ATT_USAGE, "public");
254
// } else if (!config.allow(Configuration.APP_PERM_REGISTER) &&
255
// !config.allow(Configuration.APP_PERM_WEBLOGSPING)) {
256
// session.setAttribute(ATT_USAGE, "closed");
257
// } else if (!config.allow(Configuration.APP_PERM_WEBLOGSPING)) {
258
// session.setAttribute(ATT_USAGE, "intranet");
259
// } else {
260
// session.setAttribute(ATT_USAGE, "custom");
261
// }
262

263     User user = Application.get().getUser();
264     if (!config.isInstalled() || !config.isConfigured() || user.isAdmin()) {
265       List JavaDoc steps = (List JavaDoc) session.getAttribute(ATT_STEPS);
266       if (steps == null) {
267         if (config.isConfigured() && null != user && user.isAdmin()) {
268           steps = new ArrayList JavaDoc(BASIC_STEPS);
269           steps.addAll(EXPERT_STEPS);
270           steps.addAll(CONFIG_STEPS);
271           steps.remove(STEP_FINISH);
272           steps.remove(STEP_ADMINISTRATOR);
273           session.setAttribute(ATT_ADVANCED, "true");
274           session.setAttribute(ATT_DEFAULTS, "true");
275           session.setAttribute(ATT_USER, user);
276         } else {
277           String JavaDoc installKey = (String JavaDoc) session.getAttribute(Configuration.APP_INSTALL_KEY);
278           if (null == installKey) {
279             installKey = request.getParameter("key");
280             if (null == installKey || !config.getInstallKey().equals(installKey)) {
281               request.setAttribute("steps", LOGIN_STEPS);
282               request.setAttribute("step", "login");
283               RequestDispatcher JavaDoc dispatcher = request.getRequestDispatcher("/admin/configure.jsp");
284               dispatcher.forward(request, response);
285               session.removeAttribute(ATT_CONFIG);
286               return;
287             }
288             session.setAttribute(Configuration.APP_INSTALL_KEY, installKey);
289           }
290
291           steps = new ArrayList JavaDoc(BASIC_STEPS);
292           if (!config.isInstalled()) {
293             steps.add(0, STEP_DATABASE);
294           }
295
296           session.setAttribute(ATT_USAGE, "public");
297         }
298       }
299
300       if (session.getAttribute(ATT_DEFAULTS) == null) {
301         Locale JavaDoc locale = request.getLocale();
302         if (null != locale.getCountry() && !"".equals(locale.getCountry())) {
303           config.set(Configuration.APP_COUNTRY, locale.getCountry());
304         }
305         if (null != locale.getLanguage() && !"".equals(locale.getLanguage())) {
306           config.set(Configuration.APP_LANGUAGE, locale.getLanguage());
307         }
308         // divide offset (ms) by an hour
309
int offset = TimeZone.getDefault().getRawOffset() / (60 * 60 * 1000);
310         String JavaDoc id = "GMT" + (offset >= 0 ? "+" : "") + offset;
311         config.set(Configuration.APP_TIMEZONE, TimeZone.getTimeZone(id).getID());
312         session.setAttribute(ATT_DEFAULTS, "true");
313       }
314
315       String JavaDoc step = request.getParameter("step");
316       if (null == step || "".equals(step)) {
317         step = request.getParameter("select");
318         if (null == step || "".equals(step)) {
319           step = (String JavaDoc) steps.get(0);
320         }
321       } else {
322         Map JavaDoc errors = checkStep(step, request, response, config);
323         if (null == errors) {
324           return;
325         } else if (errors.size() == 0) {
326           if (request.getParameter("finish") != null) {
327             Map JavaDoc params = request.getParameterMap();
328             Iterator JavaDoc iterator = params.keySet().iterator();
329             Map JavaDoc paramMap = new HashMap JavaDoc();
330             while (iterator.hasNext()) {
331               String JavaDoc key = (String JavaDoc) iterator.next();
332               String JavaDoc[] values = (String JavaDoc[]) params.get(key);
333               paramMap.put(key, values[0]);
334             }
335
336             try {
337               InitializeDatabase.init(config, new OutputStreamWriter JavaDoc(System.out));
338               response.sendRedirect(config.getUrl());
339               return;
340             } catch (Exception JavaDoc e) {
341               // restore config just to be sure
342
errors.put("fatal", e.getMessage());
343               e.printStackTrace();
344             }
345           } else {
346             if (request.getParameter("next") != null) {
347               int idx = steps.indexOf(step);
348               // if we see a "next" and this is the end it must be expert settings
349
if (null != request.getParameter(ATT_ADVANCED)) {
350                 session.setAttribute(ATT_ADVANCED, "true");
351                 if (request.getParameter("advanced.all") != null) {
352                   steps = addSteps(steps, EXPERT_STEPS);
353                 } else {
354                   List JavaDoc list = new ArrayList JavaDoc();
355                   Iterator JavaDoc it = request.getParameterMap().keySet().iterator();
356                   while (it.hasNext()) {
357                     String JavaDoc advStep = (String JavaDoc) it.next();
358                     if (advStep.startsWith("advanced.step.")) {
359                       advStep = advStep.substring("advanced.step.".length());
360                       list.add(advStep);
361                     }
362                   }
363                   addSteps(steps, list);
364                 }
365                 step = (String JavaDoc) steps.get(idx);
366               } else {
367                 step = (String JavaDoc) steps.get(idx + 1);
368               }
369             } else if (request.getParameter("previous") != null) {
370               int idx = steps.indexOf(step);
371               step = (String JavaDoc) steps.get(idx - 1);
372             } else if (request.getParameter("save") != null) {
373               SnipSpace space = (SnipSpace) Components.getComponent(SnipSpace.class);
374               ByteArrayOutputStream JavaDoc configStream = new ByteArrayOutputStream JavaDoc();
375               config.store(configStream);
376               Snip configSnip = space.load(Configuration.SNIPSNAP_CONFIG);
377               configSnip.setContent(new String JavaDoc(configStream.toString("UTF-8")));
378               space.store(configSnip);
379
380               FileOutputStream JavaDoc globalsOs = new FileOutputStream JavaDoc(new File JavaDoc(config.getWebInfDir(), "application.conf"));
381               config.storeGlobals(globalsOs);
382               globalsOs.flush();
383               globalsOs.close();
384             }
385           }
386         } else {
387           request.setAttribute(ATT_ERRORS, errors);
388         }
389       }
390
391       if (!request.getContextPath().equals(config.getPath())) {
392         config.setPath(request.getContextPath());
393       }
394
395       session.setAttribute(ATT_STEP, step);
396       session.setAttribute(ATT_STEPS, steps);
397       RequestDispatcher JavaDoc dispatcher = request.getRequestDispatcher("/admin/configure.jsp");
398       dispatcher.forward(request, response);
399       if (config.isConfigured()) {
400         session.removeAttribute(ATT_CONFIG);
401       }
402       return;
403     }
404     session.removeAttribute(ATT_CONFIG);
405     response.sendRedirect(config.getUrl());
406   }
407
408
409   private Map JavaDoc checkStep(String JavaDoc step,
410                         HttpServletRequest JavaDoc request,
411                         HttpServletResponse JavaDoc response,
412                         Configuration config) {
413     Map JavaDoc errors = new HashMap JavaDoc();
414
415     if (handlers.containsKey(step)) {
416       SetupHandler handler = (SetupHandler) handlers.get(step);
417       return handler.setup(request, response, config, errors);
418     } else {
419       System.err.println("ConfigureServlet: unknown step: " + step);
420     }
421
422     return errors;
423   }
424
425   private List JavaDoc addSteps(List JavaDoc steps, List JavaDoc toAdd) {
426     steps.remove(STEP_FINISH);
427     Iterator JavaDoc it = toAdd.iterator();
428     while (it.hasNext()) {
429       String JavaDoc step = (String JavaDoc) it.next();
430       if (!steps.contains(step)) {
431         steps.add(step);
432       }
433     }
434     steps.add(STEP_FINISH);
435     return steps;
436   }
437 }
438
Popular Tags