KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > snipsnap > net > filter > InitFilter


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.filter;
26
27 import org.radeox.util.i18n.ResourceManager;
28 import org.radeox.util.logging.LogHandler;
29 import org.radeox.util.logging.Logger;
30 import org.snipsnap.app.Application;
31 import org.snipsnap.app.ApplicationManager;
32 import org.snipsnap.config.Configuration;
33 import org.snipsnap.config.ConfigurationManager;
34 import org.snipsnap.config.ConfigurationProxy;
35 import org.snipsnap.config.Globals;
36 import org.snipsnap.config.ServerConfiguration;
37 import org.snipsnap.container.Components;
38 import org.snipsnap.container.SessionService;
39 import org.snipsnap.snip.Snip;
40 import org.snipsnap.snip.SnipLink;
41 import org.snipsnap.snip.SnipSpace;
42 import org.snipsnap.snip.SnipSpaceFactory;
43 import org.snipsnap.user.Digest;
44 import org.snipsnap.user.User;
45
46 import javax.servlet.Filter JavaDoc;
47 import javax.servlet.FilterChain JavaDoc;
48 import javax.servlet.FilterConfig JavaDoc;
49 import javax.servlet.RequestDispatcher JavaDoc;
50 import javax.servlet.ServletContext JavaDoc;
51 import javax.servlet.ServletException JavaDoc;
52 import javax.servlet.ServletRequest JavaDoc;
53 import javax.servlet.ServletResponse JavaDoc;
54 import javax.servlet.http.HttpServletRequest JavaDoc;
55 import javax.servlet.http.HttpServletResponse JavaDoc;
56 import javax.servlet.http.HttpSession JavaDoc;
57 import java.io.BufferedReader JavaDoc;
58 import java.io.ByteArrayInputStream JavaDoc;
59 import java.io.File JavaDoc;
60 import java.io.FileInputStream JavaDoc;
61 import java.io.FileOutputStream JavaDoc;
62 import java.io.IOException JavaDoc;
63 import java.io.InputStreamReader JavaDoc;
64 import java.net.URL JavaDoc;
65 import java.util.Collection JavaDoc;
66 import java.util.Date JavaDoc;
67 import java.util.HashMap JavaDoc;
68 import java.util.Iterator JavaDoc;
69 import java.util.Map JavaDoc;
70
71 /**
72  * A ServletFilter that takes care of uninstalled web applications and creating the
73  * application object and parameter information for servlets down the chain.
74  *
75  * @author Matthias L. Jugel
76  * @version $Id: InitFilter.java 1849 2006-02-08 11:19:12Z leo $
77  */

78 public class InitFilter implements Filter JavaDoc {
79   // private final static String
80
private Globals globals = null;
81   private boolean startUpDone = false;
82
83   public void init(FilterConfig JavaDoc filterConfig) throws ServletException JavaDoc {
84     ServletContext JavaDoc context = filterConfig.getServletContext();
85
86     // create globals configuration by getting an instance and loading application.conf
87
globals = ConfigurationProxy.getInstance();
88
89     // check servlet context and then local servlet parameter or assume WEB-INF
90
String JavaDoc configParam = (String JavaDoc) context.getAttribute(ServerConfiguration.INIT_PARAM);
91     if (null == configParam) {
92       System.out.println("SnipSnap " + globals.getVersion());
93       BufferedReader JavaDoc br = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(getClass().getResourceAsStream("/defaults/copyright.txt")));
94       try {
95         String JavaDoc line;
96         while (null != (line = br.readLine())) {
97           System.out.println(line);
98         }
99       } catch (IOException JavaDoc e) {
100         // create copyright output if the copyrights file was not found
101
System.out.println("Copyright (c) Fraunhofer Gesellschaft");
102         System.out.println("Fraunhofer Institute for Computer Architecture and Software Technology");
103         System.out.println("All Rights Reserved. See License Agreement for terms and conditions of use.");
104       }
105
106       String JavaDoc initParam = context.getInitParameter(ServerConfiguration.INIT_PARAM);
107       if (null != initParam) {
108         configParam = context.getRealPath(initParam);
109       }
110     }
111     if (null == configParam) {
112       configParam = context.getRealPath("/WEB-INF/application.conf");
113     }
114
115
116     // create globals configuration by getting an instance and loading application.conf
117
globals = ConfigurationProxy.getInstance();
118     try {
119       globals.loadGlobals(new FileInputStream JavaDoc(configParam));
120     } catch (Exception JavaDoc e) {
121       System.err.println("InitFilter: unable to load globals: " + configParam + ": " + e.getMessage());
122     }
123
124     String JavaDoc installKey = globals.getInstallKey();
125     if (null == installKey || "".equals(installKey)) {
126       globals.setInstallKey(Digest.getDigest("" + new Date JavaDoc()).substring(0, 5).toLowerCase());
127       System.out.println(">> Your installation key is '" + globals.getInstallKey() + "'");
128       System.out.println(">> Remember it, you will need this key to install new instances.");
129       try {
130         globals.storeGlobals(new FileOutputStream JavaDoc(configParam));
131       } catch (Exception JavaDoc e) {
132         System.err.println("InitFilter: unable to store install key: " + e.getMessage());
133       }
134     }
135
136     globals.setWebInfDir(new File JavaDoc(context.getRealPath("WEB-INF")));
137
138     // initalize logger before starting to load configurations
139
String JavaDoc logger = globals.getLogger();
140     try {
141       Logger.setHandler((LogHandler) Class.forName(logger).newInstance());
142     } catch (Exception JavaDoc e) {
143       System.err.println("InitFilter: LogHandler not found: " + logger);
144     }
145
146     if (!globals.isInstalled()) {
147       System.out.println(">> Please finish the installation, visit");
148       System.out.println(">> " + ((Configuration) globals).getUrl() + "?key=" + globals.getInstallKey());
149     } else {
150       loadApplicationContexts();
151     }
152     startUpDone = true;
153   }
154
155   private void loadApplicationContexts() {
156     ApplicationManager appManager = (ApplicationManager) Components.getComponent(ApplicationManager.class);
157     Collection JavaDoc prefixes = appManager.getPrefixes();
158     Iterator JavaDoc prefixIt = prefixes.iterator();
159     Application app = Application.get();
160     int okCount = 0;
161     boolean weblogsPing = false;
162     while (prefixIt.hasNext()) {
163       String JavaDoc prefix = (String JavaDoc) prefixIt.next();
164       String JavaDoc appOid = appManager.getApplication(prefix);
165       app.storeObject(Application.OID, appOid);
166
167       System.out.print(">> Loading: " + prefix + " ");
168       Configuration appConfig = ConfigurationProxy.newInstance();
169       SnipSpace space = (SnipSpace) Components.getComponent(SnipSpace.class);
170       if (space.exists(Configuration.SNIPSNAP_CONFIG)) {
171         Snip configSnip = space.load(Configuration.SNIPSNAP_CONFIG);
172         String JavaDoc configContent = configSnip.getContent();
173         try {
174           appConfig.load(new ByteArrayInputStream JavaDoc(configContent.getBytes()));
175           okCount++;
176           System.out.print("(" + appConfig.getName() + ", " + appConfig.getUrl() + ")");
177         } catch (IOException JavaDoc e) {
178           System.out.print("ERROR: " + e.getMessage());
179           continue;
180         }
181         ConfigurationManager.getInstance().addConfiguration(appOid, appConfig);
182       } else {
183         System.out.print("(NOT CONFIGURED)");
184       }
185       weblogsPing = appConfig.allow(Configuration.APP_PERM_WEBLOGSPING);
186       System.out.println();
187     }
188     if (weblogsPing) {
189       System.out.println(">> WARNING: Weblogs ping is enabled for some instances.\n" +
190                          ">> This means that SnipSnap sends notifications to hosts on the internet\n" +
191                          ">> when your weblog changes. To turn this off take a look at the FAQ at\n" +
192                          ">> http://snipsnap.org/space/faq");
193     }
194     System.out.println(">> Installation key: " + globals.getInstallKey());
195     System.out.println(">> Loaded " + okCount + " instances (" + (prefixes.size() - okCount) + " not configured).");
196   }
197
198   public void destroy() {
199     //config = null;
200
}
201
202   public void doFilter(ServletRequest JavaDoc req, ServletResponse JavaDoc response, FilterChain JavaDoc chain) throws IOException JavaDoc, ServletException JavaDoc {
203     // make sure it's an http servlet request
204
HttpServletRequest JavaDoc request = (HttpServletRequest JavaDoc) req;
205
206     if (!startUpDone) {
207       ((HttpServletResponse JavaDoc) response).sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
208                                                  "Startup in progress, please wait ...");
209       return;
210     }
211
212     String JavaDoc path = request.getServletPath();
213
214     HttpSession JavaDoc session = request.getSession();
215     Application app = Application.forceGet();
216     ConfigurationManager configManager = ConfigurationManager.getInstance();
217     ApplicationManager appManager = null;
218
219     // initialize resource manager with the browser locale and fallbacks
220
ResourceManager resourceManager = ResourceManager.forceGet();
221     resourceManager.setLocale(request.getLocale(), request.getLocales());
222
223     if (globals.isInstalled()) {
224       appManager = (ApplicationManager) Components.getComponent(ApplicationManager.class);
225     }
226
227     String JavaDoc prefix = "/";
228     String JavaDoc appOid = null;
229
230     // we need the path again, to make sure it is encoded correctly
231
path = request.getServletPath();
232     if (path != null && path.length() > 1) {
233       int prefixEnd = path.indexOf("/", 1);
234       String JavaDoc checkPrefix = null;
235       if (prefixEnd > 1) {
236         checkPrefix = path.substring(0, prefixEnd);
237       } else {
238         checkPrefix = path;
239       }
240       if (appManager != null && appManager.getPrefixes().contains(checkPrefix)) {
241         prefix = checkPrefix;
242       }
243     }
244
245     Configuration appConfig = null;
246     // get application manager and application oid is possible
247
if (globals.isInstalled()) {
248       appOid = appManager.getApplication(prefix);
249       appConfig = configManager.getConfiguration(appOid);
250       app.setConfiguration(appConfig);
251       app.storeObject(Application.OID, appOid);
252     }
253
254     // make sure XML-RPC is handled directly after determining the instance
255
if (path.startsWith("/RPC2")) {
256       if (globals.isInstalled()) {
257         chain.doFilter(request, response);
258       } else {
259         ((HttpServletResponse JavaDoc) response).sendError(HttpServletResponse.SC_PRECONDITION_FAILED,
260                                                    "Please finish database installation first.");
261       }
262       return;
263     }
264
265     // configure the url (base context path) for the current request
266
if (appConfig != null && "true".equals(appConfig.getRealAutodetect())) {
267       // apache proxies provide the host and port of the original request
268
// however, they do not provide the context path, TODO maybe Apache 2
269
String JavaDoc xForwardedHost = request.getHeader("X-Forwarded-Host");
270       if (xForwardedHost != null) {
271         String JavaDoc protocol = appConfig.get(Configuration.APP_REAL_PROTOCOL, "http");
272         String JavaDoc contextPath = appConfig.get(Configuration.APP_REAL_PATH, "");
273
274         int colonIndex = xForwardedHost.indexOf(':');
275         String JavaDoc host = xForwardedHost;
276         if (colonIndex != -1) {
277           host = host.substring(0, colonIndex);
278           int port = Integer.parseInt(xForwardedHost.substring(colonIndex + 1));
279           app.storeObject(Application.URL, new URL JavaDoc(protocol, host, port, contextPath));
280         } else {
281           app.storeObject(Application.URL, new URL JavaDoc(protocol, host, contextPath));
282         }
283       } else {
284         String JavaDoc protocol = new URL JavaDoc(request.getRequestURL().toString()).getProtocol();
285         String JavaDoc host = request.getServerName();
286         int port = request.getServerPort();
287         String JavaDoc contextPath = request.getContextPath() + ("/".equals(prefix) ? "" : prefix);
288
289         if (port != 80) {
290           app.storeObject(Application.URL, new URL JavaDoc(protocol, host, port, contextPath));
291         } else {
292           app.storeObject(Application.URL, new URL JavaDoc(protocol, host, contextPath));
293         }
294       }
295 // System.out.println("autoconfigured url: " + appConfig.getUrl());
296
}
297
298     //System.out.println("appManager: "+appManager+", appConfig="+appConfig+", "+(appConfig != null ? ""+appConfig.isConfigured() : "not configured"));
299
// make sure we do not enter the default web application unless it's fully installed
300
if (null == appManager || null == appConfig || !appConfig.isConfigured()) {
301       if (path == null || !(path.startsWith("/admin") || path.startsWith("/images"))) {
302         String JavaDoc queryString = request.getQueryString();
303         queryString = (null == queryString || "".equals(queryString) ? "" : queryString + "&") + "prefix=" + prefix;
304         ((HttpServletResponse JavaDoc) response).sendRedirect(request.getContextPath() + "/admin/configure?" + queryString);
305         return;
306       }
307     } else {
308       if (!"/".equals(prefix)) {
309         path = path.substring(prefix.length());
310       }
311
312       request.setAttribute(Configuration.APP_PREFIX, prefix);
313
314       session.setAttribute("app", app);
315       session.setAttribute("space", SnipSpaceFactory.getInstance());
316
317       // check for a logged in user
318
SessionService service = (SessionService) Components.getComponent(SessionService.class);
319       User user = service.getUser(request, (HttpServletResponse JavaDoc) response);
320       if(null == user) {
321         // someone else did something and is responsible for status codes
322
return;
323       }
324       app.setUser(user, session);
325
326       Iterator JavaDoc paramIt = request.getParameterMap().keySet().iterator();
327       Map JavaDoc paramMap = new HashMap JavaDoc();
328       while (paramIt.hasNext()) {
329         String JavaDoc key = (String JavaDoc) paramIt.next();
330         paramMap.put(key, request.getParameter(key));
331       }
332       String JavaDoc uri = (String JavaDoc) request.getAttribute("URI");
333       if (uri != null) {
334         paramMap.put("URI", appConfig.getUrl(uri));
335       } else {
336         String JavaDoc pathInfo = request.getPathInfo();
337         paramMap.put("URI", appConfig.getUrl((path != null ? path : "") +
338                                              (pathInfo != null ? pathInfo : "")));
339       }
340       paramMap.put("RSS", appConfig.getUrl("/exec/rss"));
341       paramMap.put("request", request);
342       app.setParameters(paramMap);
343     }
344
345     if (!"/".equals(prefix)) {
346       if ("".equals(path)) {
347         path = "index.jsp";
348       }
349       // TODO: hack, find a way not to re-encode the path request
350
if (request.getClass().getName().startsWith("org.mortbay")) {
351         path = SnipLink.encode(path);
352       }
353       // try to send this request to the real servlets
354
RequestDispatcher JavaDoc dispatcher = request.getRequestDispatcher(path);
355       if (dispatcher != null) {
356         dispatcher.forward(request, response);
357         return;
358       }
359     }
360
361     // apply the chain
362
chain.doFilter(request, response);
363   }
364 }
365
Popular Tags