KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > blojsom > plugin > admin > ThemeSwitcherPlugin


1 /**
2  * Copyright (c) 2003-2006, David A. Czarnecki
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are met:
7  *
8  * Redistributions of source code must retain the above copyright notice, this list of conditions and the
9  * following disclaimer.
10  * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
11  * following disclaimer in the documentation and/or other materials provided with the distribution.
12  * Neither the name of "David A. Czarnecki" and "blojsom" nor the names of its contributors may be used to
13  * endorse or promote products derived from this software without specific prior written permission.
14  * Products derived from this software may not be called "blojsom", nor may "blojsom" appear in their name,
15  * without prior written permission of David A. Czarnecki.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
18  * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
19  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
20  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
21  * EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
26  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
27  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
29  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */

31 package org.blojsom.plugin.admin;
32
33 import org.apache.commons.logging.Log;
34 import org.apache.commons.logging.LogFactory;
35 import org.blojsom.blog.Blog;
36 import org.blojsom.blog.Entry;
37 import org.blojsom.event.EventBroadcaster;
38 import org.blojsom.plugin.PluginException;
39 import org.blojsom.plugin.admin.event.ProcessRequestEvent;
40 import org.blojsom.util.BlojsomConstants;
41 import org.blojsom.util.BlojsomUtils;
42 import org.blojsom.fetcher.Fetcher;
43 import org.blojsom.fetcher.FetcherException;
44
45 import javax.servlet.http.HttpServletRequest JavaDoc;
46 import javax.servlet.http.HttpServletResponse JavaDoc;
47 import java.io.File JavaDoc;
48 import java.io.IOException JavaDoc;
49 import java.util.*;
50
51 /**
52  * ThemeSwitcherPlugin
53  *
54  * @author David Czarnecki
55  * @version $Id: ThemeSwitcherPlugin.java,v 1.2 2006/04/26 02:10:49 czarneckid Exp $
56  * @since blojsom 3.0
57  */

58 public class ThemeSwitcherPlugin extends WebAdminPlugin {
59
60     private Log _logger = LogFactory.getLog(ThemeSwitcherPlugin.class);
61
62     // Localization constants
63
private static final String JavaDoc FAILED_PERMISSION_KEY = "failed.theme.switch.permission.text";
64     private static final String JavaDoc NONE_SELECTED_KEY = "no.theme.flavor.selected.text";
65     private static final String JavaDoc ADMIN_FLAVOR_PROTECTED_KEY = "admin.flavor.protected.text";
66     private static final String JavaDoc FAILED_THEME_TEMPLATE_COPY_KEY = "failed.theme.template.copy.text";
67     private static final String JavaDoc FAILED_FLAVOR_WRITE_KEY = "failed.flavor.write.text";
68     private static final String JavaDoc THEME_SWITCHED_KEY = "theme.switched.text";
69
70     // Pages
71
private static final String JavaDoc THEME_SWITCHER_SETTINGS_PAGE = "/org/blojsom/plugin/admin/templates/admin-theme-switcher-settings";
72
73     // Context variables
74
private static final String JavaDoc THEME_SWITCHER_PLUGIN_AVAILABLE_THEMES = "THEME_SWITCHER_PLUGIN_AVAILABLE_THEMES";
75     private static final String JavaDoc THEME_SWITCHER_PLUGIN_FLAVORS = "THEME_SWITCHER_PLUGIN_FLAVORS";
76     private static final String JavaDoc THEME_SWITCHER_PLUGIN_DEFAULT_FLAVOR = "THEME_SWITCHER_PLUGIN_DEFAULT_FLAVOR";
77     private static final String JavaDoc CURRENT_HTML_THEME = "CURRENT_HTML_THEME";
78
79     // Actions
80
private static final String JavaDoc SWITCH_THEME_ACTION = "switch-theme";
81
82     // Form items
83
private static final String JavaDoc THEME = "theme";
84     private static final String JavaDoc FLAVOR = "flavor-name";
85
86     // Permissions
87
private static final String JavaDoc SWITCH_THEME_PERMISSION = "switch_theme_permission";
88     private static final String JavaDoc DEFAULT_THEMES_DIRECTORY = "/themes/";
89     private static final String JavaDoc THEMES_DIRECTORY_IP = "themes-directory";
90
91     private String JavaDoc _themesDirectory;
92     private Properties _blojsomProperties;
93     private Fetcher _fetcher;
94     private EventBroadcaster _eventBroadcaster;
95
96     /**
97      * Default constructor
98      */

99     public ThemeSwitcherPlugin() {
100     }
101
102     /**
103      * Set the {@link EventBroadcaster}
104      *
105      * @param eventBroadcaster {@link EventBroadcaster}
106      */

107     public void setEventBroadcaster(EventBroadcaster eventBroadcaster) {
108         _eventBroadcaster = eventBroadcaster;
109     }
110
111     /**
112      * Set the {@link Fetcher}
113      *
114      * @param fetcher {@link Fetcher}
115      */

116     public void setFetcher(Fetcher fetcher) {
117         _fetcher = fetcher;
118     }
119
120     /**
121      * Set the default blojsom properties
122      *
123      * @param blojsomProperties Default blojsom properties
124      */

125     public void setBlojsomProperties(Properties blojsomProperties) {
126         _blojsomProperties = blojsomProperties;
127     }
128
129     /**
130      * Initialize this plugin. This method only called when the plugin is instantiated.
131      *
132      * @throws org.blojsom.plugin.PluginException
133      * If there is an error initializing the plugin
134      */

135     public void init() throws PluginException {
136         super.init();
137
138         _themesDirectory = _blojsomProperties.getProperty(THEMES_DIRECTORY_IP);
139         if (BlojsomUtils.checkNullOrBlank(_themesDirectory)) {
140             _themesDirectory = DEFAULT_THEMES_DIRECTORY;
141         }
142
143         _themesDirectory = BlojsomUtils.checkStartingAndEndingSlash(_themesDirectory);
144     }
145
146     /**
147      * Return the display name for the plugin
148      *
149      * @return Display name for the plugin
150      */

151     public String JavaDoc getDisplayName() {
152         return "Theme Switcher plugin";
153     }
154
155     /**
156      * Return the name of the initial editing page for the plugin
157      *
158      * @return Name of the initial editing page for the plugin
159      */

160     public String JavaDoc getInitialPage() {
161         return THEME_SWITCHER_SETTINGS_PAGE;
162     }
163
164     /**
165      * Retrieve the list of directories (theme names) from the themes installation directory
166      *
167      * @return List of theme names available
168      */

169     protected String JavaDoc[] getAvailableThemes() {
170         ArrayList themes = new ArrayList(0);
171
172         File JavaDoc themesDirectory = new File JavaDoc(_servletConfig.getServletContext().getRealPath("/") + BlojsomConstants.DEFAULT_CONFIGURATION_BASE_DIRECTORY + _themesDirectory);
173
174         if (themesDirectory.exists() && themesDirectory.isDirectory()) {
175             File JavaDoc[] themesInstalled = themesDirectory.listFiles(BlojsomUtils.getDirectoryFilter());
176             if (themesInstalled != null && themesInstalled.length > 0) {
177                 for (int i = 0; i < themesInstalled.length; i++) {
178                     File JavaDoc installedTheme = themesInstalled[i];
179                     themes.add(installedTheme.getName());
180                 }
181             }
182         }
183
184         String JavaDoc[] availableThemes = (String JavaDoc[]) themes.toArray(new String JavaDoc[themes.size()]);
185         Arrays.sort(availableThemes);
186
187         return availableThemes;
188     }
189
190     /**
191      * Process the blog entries
192      *
193      * @param httpServletRequest Request
194      * @param httpServletResponse Response
195      * @param blog {@link Blog} instance
196      * @param context Context
197      * @param entries Blog entries retrieved for the particular request
198      * @return Modified set of blog entries
199      * @throws org.blojsom.plugin.PluginException
200      * If there is an error processing the blog entries
201      */

202     public Entry[] process(HttpServletRequest JavaDoc httpServletRequest, HttpServletResponse JavaDoc httpServletResponse, Blog blog, Map context, Entry[] entries) throws PluginException {
203         entries = super.process(httpServletRequest, httpServletResponse, blog, context, entries);
204         String JavaDoc page = BlojsomUtils.getRequestValue(BlojsomConstants.PAGE_PARAM, httpServletRequest);
205
206         String JavaDoc username = getUsernameFromSession(httpServletRequest, blog);
207         if (!checkPermission(blog, null, username, SWITCH_THEME_PERMISSION)) {
208             httpServletRequest.setAttribute(BlojsomConstants.PAGE_PARAM, ADMIN_ADMINISTRATION_PAGE);
209             addOperationResultMessage(context, getAdminResource(FAILED_PERMISSION_KEY, FAILED_PERMISSION_KEY, blog.getBlogAdministrationLocale()));
210
211             return entries;
212         }
213
214         if (ADMIN_LOGIN_PAGE.equals(page)) {
215             return entries;
216         } else {
217             String JavaDoc action = BlojsomUtils.getRequestValue(ACTION_PARAM, httpServletRequest);
218
219             context.put(THEME_SWITCHER_PLUGIN_AVAILABLE_THEMES, getAvailableThemes());
220             context.put(THEME_SWITCHER_PLUGIN_FLAVORS, new TreeMap(blog.getTemplates()));
221             context.put(THEME_SWITCHER_PLUGIN_DEFAULT_FLAVOR, blog.getBlogDefaultFlavor());
222             String JavaDoc currentHtmlFlavor = (String JavaDoc) blog.getTemplates().get(BlojsomConstants.DEFAULT_FLAVOR_HTML);
223             currentHtmlFlavor = currentHtmlFlavor.substring(0, currentHtmlFlavor.indexOf('.'));
224             context.put(CURRENT_HTML_THEME, currentHtmlFlavor);
225
226             if (SWITCH_THEME_ACTION.equals(action)) {
227                 String JavaDoc theme = BlojsomUtils.getRequestValue(THEME, httpServletRequest);
228                 String JavaDoc flavor = BlojsomUtils.getRequestValue(FLAVOR, httpServletRequest);
229
230                 if (BlojsomUtils.checkNullOrBlank(theme) || BlojsomUtils.checkNullOrBlank(flavor)) {
231                     addOperationResultMessage(context, getAdminResource(NONE_SELECTED_KEY, NONE_SELECTED_KEY, blog.getBlogAdministrationLocale()));
232                     return entries;
233                 }
234
235                 if ("admin".equalsIgnoreCase(flavor)) {
236                     addOperationResultMessage(context, getAdminResource(ADMIN_FLAVOR_PROTECTED_KEY, ADMIN_FLAVOR_PROTECTED_KEY, blog.getBlogAdministrationLocale()));
237                     return entries;
238                 }
239
240                 File JavaDoc copyFromTemplatesDirectory = new File JavaDoc(_servletConfig.getServletContext().getRealPath("/") +
241                         BlojsomConstants.DEFAULT_CONFIGURATION_BASE_DIRECTORY + _themesDirectory + theme +
242                         "/" + _blojsomProperties.getProperty(BlojsomConstants.TEMPLATES_DIRECTORY_IP));
243
244                 File JavaDoc[] templateFiles = copyFromTemplatesDirectory.listFiles();
245                 String JavaDoc mainTemplate = null;
246
247                 if (templateFiles != null && templateFiles.length > 0) {
248                     for (int i = 0; i < templateFiles.length; i++) {
249                         File JavaDoc templateFile = templateFiles[i];
250                         if (!templateFile.isDirectory()) {
251                             if (templateFile.getName().startsWith(theme + ".")) {
252                                 mainTemplate = templateFile.getName();
253                             }
254                         }
255                     }
256                 }
257
258                 File JavaDoc copyToTemplatesDirectory = new File JavaDoc(_servletConfig.getServletContext().getRealPath("/") +
259                         BlojsomConstants.DEFAULT_CONFIGURATION_BASE_DIRECTORY +
260                         _blojsomProperties.getProperty(BlojsomConstants.BLOGS_DIRECTORY_IP) + blog.getBlogId() +
261                         "/" + _blojsomProperties.getProperty(BlojsomConstants.TEMPLATES_DIRECTORY_IP));
262
263                 try {
264                     BlojsomUtils.copyDirectory(copyFromTemplatesDirectory, copyToTemplatesDirectory);
265                 } catch (IOException JavaDoc e) {
266                     _logger.error(e);
267                     addOperationResultMessage(context, getAdminResource(FAILED_THEME_TEMPLATE_COPY_KEY, FAILED_THEME_TEMPLATE_COPY_KEY, blog.getBlogAdministrationLocale()));
268                 }
269
270                 File JavaDoc copyFromResourcesDirectory = new File JavaDoc(_servletConfig.getServletContext().getRealPath("/") +
271                         BlojsomConstants.DEFAULT_CONFIGURATION_BASE_DIRECTORY + _themesDirectory + theme + "/" +
272                         _blojsomProperties.getProperty(BlojsomConstants.RESOURCES_DIRECTORY_IP));
273                 File JavaDoc copyToResourcesDirectory = new File JavaDoc(_servletConfig.getServletContext().getRealPath("/") +
274                         _blojsomProperties.getProperty(BlojsomConstants.RESOURCES_DIRECTORY_IP) + blog.getBlogId() + "/");
275
276                 try {
277                     BlojsomUtils.copyDirectory(copyFromResourcesDirectory, copyToResourcesDirectory);
278                 } catch (IOException JavaDoc e) {
279                     _logger.error(e);
280                     addOperationResultMessage(context, getAdminResource(FAILED_THEME_TEMPLATE_COPY_KEY, FAILED_THEME_TEMPLATE_COPY_KEY, blog.getBlogAdministrationLocale()));
281                 }
282
283                 try {
284                     if (mainTemplate == null) {
285                         mainTemplate = (String JavaDoc) blog.getTemplates().get(flavor);
286
287                         _logger.debug("No main template supplied for " + theme + " theme. Using existing template for flavor: " + mainTemplate);
288                     } else {
289                         if (BlojsomConstants.DEFAULT_FLAVOR_HTML.equals(flavor)) {
290                             mainTemplate += ", " + "text/html;charset=UTF-8";
291                         }
292                     }
293
294                     Map templates = new HashMap(blog.getTemplates());
295                     templates.put(flavor, mainTemplate);
296                     blog.setTemplates(templates);
297
298                     _fetcher.saveBlog(blog);
299                 } catch (FetcherException e) {
300                     _logger.error(e);
301                     addOperationResultMessage(context, getAdminResource(FAILED_FLAVOR_WRITE_KEY, FAILED_FLAVOR_WRITE_KEY, blog.getBlogAdministrationLocale()));
302
303                     return entries;
304                 }
305
306                 currentHtmlFlavor = (String JavaDoc) blog.getTemplates().get(BlojsomConstants.DEFAULT_FLAVOR_HTML);
307                 currentHtmlFlavor = currentHtmlFlavor.substring(0, currentHtmlFlavor.indexOf('.'));
308                 context.put(CURRENT_HTML_THEME, currentHtmlFlavor);
309
310                 addOperationResultMessage(context, formatAdminResource(THEME_SWITCHED_KEY, THEME_SWITCHED_KEY, blog.getBlogAdministrationLocale(), new Object JavaDoc[]{theme, flavor}));
311                 _eventBroadcaster.processEvent(new ProcessRequestEvent(this, new Date(), blog, httpServletRequest, httpServletResponse, context));
312             } else {
313                 _eventBroadcaster.processEvent(new ProcessRequestEvent(this, new Date(), blog, httpServletRequest, httpServletResponse, context));
314
315                 context.put(THEME_SWITCHER_PLUGIN_AVAILABLE_THEMES, getAvailableThemes());
316             }
317         }
318
319         return entries;
320     }
321 }
Popular Tags