File Source: RollerContext.java
1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. The ASF licenses this file to You
4 * under the Apache License, Version 2.0 (the "License"); you may not
5 * use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License. For additional information regarding
15 * copyright in this work, please see the NOTICE file in the top level
16 * directory of this distribution.
17 */
18
19 package org.apache.roller.weblogger.ui.core;
20
21 import java.io.File;
22 import java.io.InputStream;
23 import java.util.Properties;
24 import javax.servlet.ServletContext;
25 import javax.servlet.ServletContextEvent;
26 import javax.servlet.ServletContextListener;
27 import org.acegisecurity.providers.ProviderManager;
28 import org.acegisecurity.providers.dao.DaoAuthenticationProvider;
29 import org.acegisecurity.providers.dao.UserCache;
30 import org.acegisecurity.providers.encoding.Md5PasswordEncoder;
31 import org.acegisecurity.providers.encoding.PasswordEncoder;
32 import org.acegisecurity.providers.encoding.ShaPasswordEncoder;
33 import org.acegisecurity.ui.webapp.AuthenticationProcessingFilterEntryPoint;
34 import org.apache.commons.logging.Log;
35 import org.apache.commons.logging.LogFactory;
36 import org.apache.log4j.PropertyConfigurator;
37 import org.apache.roller.planet.business.GuicePlanetProvider;
38 import org.apache.roller.weblogger.WebloggerException;
39 import org.apache.roller.weblogger.business.BootstrapException;
40 import org.apache.roller.weblogger.business.startup.StartupException;
41 import org.apache.roller.weblogger.config.WebloggerConfig;
42 import org.apache.roller.weblogger.business.WebloggerFactory;
43 import org.apache.roller.planet.business.PlanetFactory;
44 import org.apache.roller.planet.business.PlanetProvider;
45 import org.apache.roller.planet.business.startup.PlanetStartup;
46 import org.apache.roller.weblogger.business.startup.WebloggerStartup;
47 import org.apache.roller.weblogger.pojos.User;
48 import org.apache.roller.weblogger.ui.core.plugins.UIPluginManager;
49 import org.apache.roller.weblogger.ui.core.plugins.UIPluginManagerImpl;
50 import org.apache.roller.weblogger.ui.core.security.AutoProvision;
51 import org.apache.roller.weblogger.util.cache.CacheManager;
52 import org.apache.velocity.runtime.RuntimeSingleton;
53 import org.springframework.context.ApplicationContext;
54 import org.springframework.web.context.ContextLoaderListener;
55 import org.springframework.web.context.support.WebApplicationContextUtils;
56
57
58 /**
59 * Initialize the Roller web application/context.
60 */
61 public class RollerContext extends ContextLoaderListener
62 implements ServletContextListener {
63
/*
P/P * Method: org.apache.roller.weblogger.ui.core.RollerContext__static_init
*
* Postconditions:
* init'ed(log)
* servletContext == null
*/
64 private static Log log = LogFactory.getLog(RollerContext.class);
65
66 private static ServletContext servletContext = null;
67
68
69 public RollerContext() {
/*
P/P * Method: void org.apache.roller.weblogger.ui.core.RollerContext()
*/
70 super();
71 }
72
73
74 /**
75 * Access to the plugin manager for the UI layer. TODO: we may want
76 * something similar to the Roller interface for the UI layer if we dont
77 * want methods like this here in RollerContext.
78 */
79 public static UIPluginManager getUIPluginManager() {
/*
P/P * Method: UIPluginManager getUIPluginManager()
*
* Preconditions:
* init'ed(org/apache/roller/weblogger/ui/core/plugins/UIPluginManagerImpl.instance)
*
* Postconditions:
* return_value == org/apache/roller/weblogger/ui/core/plugins/UIPluginManagerImpl.instance
* init'ed(return_value)
*/
80 return UIPluginManagerImpl.getInstance();
81 }
82
83
84 /**
85 * Get the ServletContext.
86 * @return ServletContext
87 */
88 public static ServletContext getServletContext() {
/*
P/P * Method: ServletContext getServletContext()
*
* Preconditions:
* init'ed(servletContext)
*
* Postconditions:
* return_value == servletContext
* init'ed(return_value)
*/
89 return servletContext;
90 }
91
92
93 /**
94 * Responds to app-init event and triggers startup procedures.
95 */
96 public void contextInitialized(ServletContextEvent sce) {
97
98 // First, initialize everything that requires no database
99
100 // Keep a reverence to ServletContext object
/*
P/P * Method: void contextInitialized(ServletContextEvent)
*
* Preconditions:
* log != null
* sce != null
*
* Presumptions:
* init'ed(java.io.File.separator)
* javax.servlet.ServletContext:getRealPath(...)@109 != null
* javax.servlet.ServletContextEvent:getServletContext(...)@101 != null
* org.apache.roller.planet.business.PlanetFactory:getPlanet(...)@187 != null
* org.apache.roller.weblogger.business.WebloggerFactory:getWeblogger(...)@159 != null
*
* Postconditions:
* (soft) servletContext != null
*
* Test Vectors:
* java.lang.String:endsWith(...)@110: {1}, {0}
* org.apache.roller.weblogger.business.WebloggerFactory:isBootstrapped(...)@168: {0}, {1}
* org.apache.roller.weblogger.business.startup.WebloggerStartup:isPrepared(...)@147: {1}, {0}
* org.apache.roller.weblogger.config.WebloggerConfig:getBooleanProperty(...)@169: {0}, {1}
*/
101 this.servletContext = sce.getServletContext();
102
103 // Call Spring's context ContextLoaderListener to initialize all the
104 // context files specified in web.xml. This is necessary because
105 // listeners don't initialize in the order specified in 2.3 containers
106 super.contextInitialized(sce);
107
108 // get the *real* path to <context>/resources
109 String ctxPath = servletContext.getRealPath("/");
110 if(!ctxPath.endsWith(File.separator))
111 ctxPath += File.separator + "resources";
112 else
113 ctxPath += "resources";
114
115 // try setting the uploads path to <context>/resources
116 // NOTE: this should go away at some point
117 // we leave it here for now to allow users to keep writing
118 // uploads into their webapp context, but this is a bad idea
119 //
120 // also, the WebloggerConfig.setUploadsDir() method is smart
121 // enough to disregard this call unless the uploads.path
122 // is set to ${webapp.context}
123 WebloggerConfig.setUploadsDir(ctxPath);
124
125 // try setting the themes path to <context>/themes
126 // NOTE: this should go away at some point
127 // we leave it here for now to allow users to keep using
128 // themes in their webapp context, but this is a bad idea
129 //
130 // also, the WebloggerConfig.setThemesDir() method is smart
131 // enough to disregard this call unless the themes.dir
132 // is set to ${webapp.context}
133 WebloggerConfig.setThemesDir(servletContext.getRealPath("/")+File.separator+"themes");
134
135
136 // Now prepare the core services of the app so we can bootstrap
137 try {
138 WebloggerStartup.prepare();
139 } catch (StartupException ex) {
140 log.fatal("Roller Weblogger startup failed during app preparation", ex);
141 return;
142 }
143
144
145 // if preparation failed or is incomplete then we are done,
146 // otherwise try to bootstrap the business tier
147 if (!WebloggerStartup.isPrepared()) {
148 StringBuffer buf = new StringBuffer();
149 buf.append("\n--------------------------------------------------------------");
150 buf.append("\nRoller Weblogger startup INCOMPLETE, user interaction required");
151 buf.append("\n--------------------------------------------------------------");
152 log.info(buf.toString());
153 } else {
154 try {
155 // trigger bootstrapping process
156 WebloggerFactory.bootstrap();
157
158 // trigger initialization process
159 WebloggerFactory.getWeblogger().initialize();
160
161 } catch (BootstrapException ex) {
162 log.fatal("Roller Weblogger bootstrap failed", ex);
163 } catch (WebloggerException ex) {
164 log.fatal("Roller Weblogger initialization failed", ex);
165 }
166
167 // Initialize Planet if necessary
168 if (WebloggerFactory.isBootstrapped()) {
169 if (WebloggerConfig.getBooleanProperty("planet.aggregator.enabled")) {
170
171 // Now prepare the core services of planet so we can bootstrap it
172 try {
173 PlanetStartup.prepare();
174 } catch (Throwable ex) {
175 log.fatal("Roller Planet startup failed during app preparation", ex);
176 return;
177 }
178
179 try {
180 // trigger planet bootstrapping process
181 // we need to use our own planet provider for integration
182 String guiceModule = WebloggerConfig.getProperty("planet.aggregator.guice.module");
183 PlanetProvider provider = new GuicePlanetProvider(guiceModule);
184 PlanetFactory.bootstrap(provider);
185
186 // and now initialize planet
187 PlanetFactory.getPlanet().initialize();
188
189 } catch (Throwable t) {
190 log.fatal("Roller Planet initialization failed", t);
191 }
192 }
193 }
194 }
195
196
197 // do a small amount of work to initialize the web tier
198 try {
199 // Initialize Acegi based on Roller configuration
200 initializeSecurityFeatures(servletContext);
201
202 // Setup Velocity template engine
203 setupVelocity();
204 } catch (WebloggerException ex) {
205 log.fatal("Error initializing Roller Weblogger web tier", ex);
206 }
207
208 }
209
210
211 /**
212 * Responds to app-destroy event and triggers shutdown sequence.
213 */
214 public void contextDestroyed(ServletContextEvent sce) {
/*
P/P * Method: void contextDestroyed(ServletContextEvent)
*
* Presumptions:
* org.apache.roller.weblogger.business.WebloggerFactory:getWeblogger(...)@215 != null
*/
215 WebloggerFactory.getWeblogger().shutdown();
216 // do we need a more generic mechanism for presentation layer shutdown?
217 CacheManager.shutdown();
218 }
219
220
221 /**
222 * Initialize the Velocity rendering engine.
223 */
224 private void setupVelocity() throws WebloggerException {
/*
P/P * Method: void setupVelocity()
*
* Preconditions:
* log != null
* servletContext != null
*
* Test Vectors:
* org.apache.roller.weblogger.config.WebloggerConfig:getBooleanProperty(...)@236: {0}, {1}
*/
225 log.info("Initializing Velocity");
226
227 // initialize the Velocity engine
228 Properties velocityProps = new Properties();
229
230 try {
231 InputStream instream = servletContext.getResourceAsStream("/WEB-INF/velocity.properties");
232
233 velocityProps.load(instream);
234
235 // need to dynamically add old macro libraries if they are enabled
236 if(WebloggerConfig.getBooleanProperty("rendering.legacyModels.enabled")) {
237 String macroLibraries = (String) velocityProps.get("velocimacro.library");
238 String oldLibraries = WebloggerConfig.getProperty("velocity.oldMacroLibraries");
239
240 // set the new value
241 velocityProps.setProperty("velocimacro.library", oldLibraries+","+macroLibraries);
242 }
243
244 log.debug("Velocity props = "+velocityProps);
245
246 // init velocity
247 RuntimeSingleton.init(velocityProps);
248
249 } catch (Exception e) {
250 throw new WebloggerException(e);
251 }
252
253 }
254
255 /**
256 * Setup Acegi security features.
257 */
258 protected void initializeSecurityFeatures(ServletContext context) {
259
/*
P/P * Method: void initializeSecurityFeatures(ServletContext)
*
* Preconditions:
* context != null
* log != null
*
* Presumptions:
* java.lang.Boolean:valueOf(...)@265 != null
* java.lang.Boolean:valueOf(...)@278 != null
* org.acegisecurity.providers.ProviderManager:getProviders(...)@273 != null
* org.apache.roller.weblogger.config.WebloggerConfig:getProperty(...)@283 != null
* org.springframework.context.ApplicationContext:getBean(...)@272 != null
* ...
*
* Test Vectors:
* java.lang.Boolean:booleanValue(...)@265: {0}, {1}
* java.lang.Boolean:booleanValue(...)@278: {0}, {1}
* java.lang.String:equalsIgnoreCase(...)@285: {0}, {1}
* java.lang.String:equalsIgnoreCase(...)@287: {0}, {1}
* org.apache.roller.weblogger.config.WebloggerConfig:getBooleanProperty(...)@300: {0}, {1}
*/
260 ApplicationContext ctx =
261 WebApplicationContextUtils.getRequiredWebApplicationContext(context);
262
263
264 String rememberMe = WebloggerConfig.getProperty("rememberme.enabled");
265 boolean rememberMeEnabled = Boolean.valueOf(rememberMe).booleanValue();
266
267 log.info("Remember Me enabled: " + rememberMeEnabled);
268
269 context.setAttribute("rememberMeEnabled", rememberMe);
270
271 if (rememberMeEnabled) {
272 ProviderManager provider = (ProviderManager) ctx.getBean("authenticationManager");
273 provider.getProviders().add(ctx.getBean("rememberMeAuthenticationProvider"));
274 }
275
276
277 String encryptPasswords = WebloggerConfig.getProperty("passwds.encryption.enabled");
278 boolean doEncrypt = Boolean.valueOf(encryptPasswords).booleanValue();
279
280 if (doEncrypt) {
281 DaoAuthenticationProvider provider =
282 (DaoAuthenticationProvider) ctx.getBean("daoAuthenticationProvider");
283 String algorithm = WebloggerConfig.getProperty("passwds.encryption.algorithm");
284 PasswordEncoder encoder = null;
285 if (algorithm.equalsIgnoreCase("SHA")) {
286 encoder = new ShaPasswordEncoder();
287 } else if (algorithm.equalsIgnoreCase("MD5")) {
288 encoder = new Md5PasswordEncoder();
289 } else {
290 log.error("Encryption algorithm '" + algorithm +
291 "' not supported, disabling encryption.");
292 }
293 if (encoder != null) {
294 provider.setPasswordEncoder(encoder);
295 log.info("Password Encryption Algorithm set to '" + algorithm + "'");
296 }
297 }
298
299
300 if (WebloggerConfig.getBooleanProperty("securelogin.enabled")) {
301 AuthenticationProcessingFilterEntryPoint entryPoint =
302 (AuthenticationProcessingFilterEntryPoint)
303 ctx.getBean("authenticationProcessingFilterEntryPoint");
304 entryPoint.setForceHttps(true);
305 }
306
307 /*
308 if (WebloggerConfig.getBooleanProperty("schemeenforcement.enabled")) {
309
310 ChannelProcessingFilter procfilter =
311 (ChannelProcessingFilter)ctx.getBean("channelProcessingFilter");
312 ConfigAttributeDefinition secureDef = new ConfigAttributeDefinition();
313 secureDef.addConfigAttribute(new SecurityConfig("REQUIRES_SECURE_CHANNEL"));
314 ConfigAttributeDefinition insecureDef = new ConfigAttributeDefinition();
315 insecureDef.addConfigAttribute(new SecurityConfig("REQUIRES_INSECURE_CHANNEL"));
316 PathBasedFilterInvocationDefinitionMap defmap =
317 (PathBasedFilterInvocationDefinitionMap)procfilter.getFilterInvocationDefinitionSource();
318
319 // add HTTPS URL path patterns to Acegi config
320 String httpsUrlsProp = WebloggerConfig.getProperty("schemeenforcement.https.urls");
321 if (httpsUrlsProp != null) {
322 String[] httpsUrls = StringUtils.stripAll(StringUtils.split(httpsUrlsProp, ",") );
323 for (int i=0; i<httpsUrls.length; i++) {
324 defmap.addSecureUrl(httpsUrls[i], secureDef);
325 }
326 }
327 // all other action URLs are non-HTTPS
328 defmap.addSecureUrl("/**<!-- need to remove this when uncommenting -->/*.do*", insecureDef);
329 }
330 */
331 }
332
333
334 /**
335 * Flush user from any caches maintained by security system.
336 */
337 public static void flushAuthenticationUserCache(String userName) {
/*
P/P * Method: void flushAuthenticationUserCache(String)
*
* Preconditions:
* init'ed(servletContext)
*
* Presumptions:
* org.springframework.web.context.support.WebApplicationContextUtils:getRequiredWebApplicationContext(...)@338 != null
*
* Test Vectors:
* org.springframework.context.ApplicationContext:getBean(...)@340: Addr_Set{null}, Inverse{null}
*/
338 ApplicationContext ctx =
339 WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
340 UserCache userCache = (UserCache)ctx.getBean("userCache");
341 if (userCache != null) {
342 userCache.removeUserFromCache(userName);
343 }
344 }
345
346
347 /**
348 * Get an instance of AutoProvision, if available in roller.properties
349 * @return AutoProvision
350 */
351 public static AutoProvision getAutoProvision() {
/*
P/P * Method: AutoProvision getAutoProvision()
*
* Preconditions:
* (soft) log != null
*
* Presumptions:
* interfaces.length@370 <= 232-1
* java.lang.Class:getInterfaces(...)@370 != null
*
* Postconditions:
* init'ed(return_value)
*
* Test Vectors:
* java.lang.Class:forName(...)@360: Inverse{null}, Addr_Set{null}
* java.lang.Object:equals(...)@372: {0}, {1}
* org.apache.roller.weblogger.config.WebloggerConfig:getProperty(...)@352: Inverse{null}, Addr_Set{null}
*/
352 String clazzName = WebloggerConfig.getProperty("users.sso.autoProvision.className");
353
354 if (null == clazzName) {
355 return null;
356 }
357
358 Class clazz;
359 try {
360 clazz = Class.forName(clazzName);
361 } catch (ClassNotFoundException e) {
362 log.warn("Unable to found specified Auto Provision class.", e);
363 return null;
364 }
365
366 if(null == clazz) {
367 return null;
368 }
369
370 Class[] interfaces = clazz.getInterfaces();
371 for (int i = 0; i < interfaces.length; i++) {
+ 372 if (interfaces[i].equals(AutoProvision.class)) {
373 try {
374 return (AutoProvision) clazz.newInstance();
375 } catch (InstantiationException e) {
376 log.warn("InstantiationException while creating: " + clazzName, e);
377 } catch (IllegalAccessException e) {
378 log.warn("IllegalAccessException while creating: " + clazzName, e);
379 }
380 }
381 }
382 return null;
383 }
384 }
SofCheck Inspector Build Version : 2.18479
| RollerContext.java |
2009-Jan-02 14:25:30 |
| RollerContext.class |
2009-Sep-04 03:12:44 |