KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sslexplorer > core > CoreUtil


1 /*
2  * SSL-Explorer
3  *
4  * Copyright (C) 2003-2006 3SP LTD. All Rights Reserved
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2 of
9  * the License, or (at your option) any later version.
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public
16  * License along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */

19             
20 package com.sslexplorer.core;
21
22 import java.io.ByteArrayOutputStream JavaDoc;
23 import java.io.File JavaDoc;
24 import java.io.FileInputStream JavaDoc;
25 import java.io.IOException JavaDoc;
26 import java.io.ObjectOutputStream JavaDoc;
27 import java.io.PrintWriter JavaDoc;
28 import java.io.Serializable JavaDoc;
29 import java.io.StringWriter JavaDoc;
30 import java.lang.reflect.Field JavaDoc;
31 import java.lang.reflect.Method JavaDoc;
32 import java.net.MalformedURLException JavaDoc;
33 import java.net.URI JavaDoc;
34 import java.net.URISyntaxException JavaDoc;
35 import java.net.URL JavaDoc;
36 import java.text.DateFormat JavaDoc;
37 import java.text.ParseException JavaDoc;
38 import java.text.SimpleDateFormat JavaDoc;
39 import java.util.ArrayList JavaDoc;
40 import java.util.Iterator JavaDoc;
41 import java.util.List JavaDoc;
42 import java.util.Locale JavaDoc;
43 import java.util.Map JavaDoc;
44 import java.util.Properties JavaDoc;
45 import java.util.StringTokenizer JavaDoc;
46 import java.util.zip.Adler32 JavaDoc;
47 import java.util.zip.CheckedInputStream JavaDoc;
48
49 import javax.servlet.ServletContext JavaDoc;
50 import javax.servlet.http.Cookie JavaDoc;
51 import javax.servlet.http.HttpServletRequest JavaDoc;
52 import javax.servlet.http.HttpServletRequestWrapper JavaDoc;
53 import javax.servlet.http.HttpServletResponse JavaDoc;
54 import javax.servlet.http.HttpSession JavaDoc;
55 import javax.servlet.http.HttpSessionBindingEvent JavaDoc;
56 import javax.servlet.http.HttpSessionBindingListener JavaDoc;
57 import javax.servlet.jsp.PageContext JavaDoc;
58 import javax.servlet.jsp.tagext.Tag JavaDoc;
59
60 import org.apache.commons.cache.Cache;
61 import org.apache.commons.cache.CacheStat;
62 import org.apache.commons.lang.StringUtils;
63 import org.apache.commons.logging.Log;
64 import org.apache.commons.logging.LogFactory;
65 import org.apache.struts.Globals;
66 import org.apache.struts.action.Action;
67 import org.apache.struts.action.ActionForm;
68 import org.apache.struts.action.ActionForward;
69 import org.apache.struts.action.ActionMapping;
70 import org.apache.struts.action.ActionMessages;
71 import org.apache.struts.config.ModuleConfig;
72 import org.apache.struts.taglib.tiles.ComponentConstants;
73 import org.apache.struts.tiles.ComponentContext;
74 import org.apache.struts.util.MessageResources;
75 import org.apache.struts.util.ModuleUtils;
76
77 import com.sslexplorer.boot.ContextHolder;
78 import com.sslexplorer.boot.Util;
79 import com.sslexplorer.core.actions.CoreAction;
80 import com.sslexplorer.core.actions.LicenseAgreementDispatchAction;
81 import com.sslexplorer.core.forms.CoreForm;
82 import com.sslexplorer.extensions.types.Plugin;
83 import com.sslexplorer.extensions.types.PluginType;
84 import com.sslexplorer.policyframework.NoPermissionException;
85 import com.sslexplorer.policyframework.Permission;
86 import com.sslexplorer.policyframework.PolicyDatabaseFactory;
87 import com.sslexplorer.policyframework.ResourceStack;
88 import com.sslexplorer.policyframework.ResourceType;
89 import com.sslexplorer.properties.Property;
90 import com.sslexplorer.properties.PropertyProfile;
91 import com.sslexplorer.properties.impl.profile.ProfilePropertyKey;
92 import com.sslexplorer.security.AuthenticationScheme;
93 import com.sslexplorer.security.Constants;
94 import com.sslexplorer.security.DefaultAuthenticationScheme;
95 import com.sslexplorer.security.LogonControllerFactory;
96 import com.sslexplorer.security.Role;
97 import com.sslexplorer.security.SessionInfo;
98 import com.sslexplorer.security.SystemDatabaseFactory;
99 import com.sslexplorer.security.User;
100 import com.sslexplorer.security.UserDatabase;
101 import com.sslexplorer.tasks.TaskHttpServletRequest;
102 import com.sslexplorer.vfs.UploadDetails;
103 import com.sslexplorer.vfs.UploadManager;
104 import com.sslexplorer.vfs.store.downloads.TempStore;
105 import com.sslexplorer.vfs.webdav.DAVUtilities;
106
107 /**
108  * Useful utility method used throught the core webapplication.
109  *
110  * @author Brett Smith <brett@3sp.com>
111  */

112 public class CoreUtil {
113     final static Log log = LogFactory.getLog(CoreUtil.class);
114
115     /**
116      * Method to get the session temp download file.
117      *
118      * @param session
119      * @return File
120      * @throws Exception
121      */

122     public static File JavaDoc getTempDownloadDirectory(SessionInfo session) throws Exception JavaDoc {
123         final File JavaDoc tempDownloadDirectory = new File JavaDoc(ContextHolder.getContext().getTempDirectory(), TempStore.TEMP_DOWNLOAD_MOUNT_NAME);
124         // create the download store if it does not exist.
125
if (!tempDownloadDirectory.exists()) {
126             if (!tempDownloadDirectory.mkdirs()) {
127                 throw new Exception JavaDoc("Could not create temporary download directory " + tempDownloadDirectory.getAbsolutePath()
128                     + ".");
129             }
130         }
131         // now create the actual session folder
132
final File JavaDoc tempSessionDownloadDirectory = new File JavaDoc(tempDownloadDirectory, session.getUser().getPrincipalName() + "."
133             + session.getHttpSession().getId());
134         if (!tempSessionDownloadDirectory.exists()) {
135             
136             // Hook for cleaning up on logout
137
session.getHttpSession().setAttribute(DownloadContent.FILES_DOWNLOAD_CLEANUP_SESSION_HOOK, new HttpSessionBindingListener JavaDoc() {
138
139                 public void valueBound(HttpSessionBindingEvent JavaDoc event) {
140                 }
141
142                 public void valueUnbound(HttpSessionBindingEvent JavaDoc event) {
143                     if(log.isInfoEnabled()) {
144                         log.info("Cleaning up temporary download directory " + tempSessionDownloadDirectory);
145                     }
146                     Util.delTree(tempSessionDownloadDirectory);
147                 }
148             });
149             
150             
151             if (!tempSessionDownloadDirectory.mkdirs()) {
152                 throw new Exception JavaDoc("Could not create temporary session download directory " + tempSessionDownloadDirectory.getAbsolutePath()
153                     + " for user "
154                     + session.getUser().getPrincipalName()
155                     + ".");
156             }
157         }
158         return tempSessionDownloadDirectory;
159     }
160
161
162     /**
163      * Store to cache, checking for serializable.
164      *
165      * @param cache cache to store object in
166      * @param key cache key
167      * @param object object to cache
168      * @param ttl time-to-live in milliseconds
169      * @param cost cost
170      */

171     public static void storeToCache(Cache cache, String JavaDoc key, Serializable JavaDoc object, long ttl, long cost) {
172         if (log.isDebugEnabled()) {
173             log.debug("Caching under " + key + ", ttl=" + ttl + ", cost="
174                     + cost);
175         }
176
177         // NOTE Temporary code to make sure policy objects are serializable, in development and testing
178
if ("true".equals(System.getProperty("sslexplorer.useDevConfig")) | "true".equals(System.getProperty("sslexplorer.testing"))) {
179             ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
180             try {
181                 ObjectOutputStream JavaDoc oos = new ObjectOutputStream JavaDoc(baos);
182                 oos.writeObject(object);
183             } catch (Exception JavaDoc e) {
184                 String JavaDoc string = "********** Failed to cache policy database object. There is probably a non-serializable object somewhere in the object graph. PLEASE FIX ME ****************";
185                 System.err
186                         .println(string);
187                 e.printStackTrace();
188                 throw new RuntimeException JavaDoc(string);
189             }
190         }
191
192         cache.store(key, object, new Long JavaDoc(ttl
193                 + System.currentTimeMillis()), cost);
194         if (log.isDebugEnabled()) {
195             log.debug("NUM_RETRIEVE_REQUESTED "
196                     + cache.getStat(CacheStat.NUM_RETRIEVE_REQUESTED));
197             log.debug("NUM_RETRIEVE_FOUND "
198                     + cache.getStat(CacheStat.NUM_RETRIEVE_FOUND));
199             log.debug("NUM_RETRIEVE_NOT_FOUND "
200                     + cache.getStat(CacheStat.NUM_RETRIEVE_NOT_FOUND));
201             log.debug("NUM_STORE_REQUESTED "
202                     + cache.getStat(CacheStat.NUM_STORE_REQUESTED));
203             log.debug("NUM_STORE_STORED "
204                     + cache.getStat(CacheStat.NUM_STORE_STORED));
205             log.debug("NUM_STORE_NOT_STORED "
206                     + cache.getStat(CacheStat.NUM_STORE_NOT_STORED));
207             log.debug("CUR_CAPACITY "
208                     + cache.getStat(CacheStat.CUR_CAPACITY));
209         }
210     }
211
212     /**
213      * Get a cookie object from a request given its name. <code>null</code>
214      * will be returned if the cookie cannot be found
215      *
216      * @param name cookie name
217      * @param request request.
218      * @return cookie object
219      */

220     public static Cookie JavaDoc getCookie(String JavaDoc name, HttpServletRequest JavaDoc request) {
221         Cookie JavaDoc[] cookies = request.getCookies();
222         if (cookies != null) {
223             for (int i = 0; i < cookies.length; i++) {
224                 if (cookies[i].getName().equals(name)) {
225                     return cookies[i];
226                 }
227             }
228         }
229         return null;
230     }
231
232     /**
233      * Get a cookie value from a request given its name. The specified default
234      * will be returned if the cookie cannot be found
235      *
236      * @param name cookie name
237      * @param request request
238      * @param defaultValue default value
239      * @return cookie value
240      */

241     public static String JavaDoc getCookieValue(String JavaDoc name, HttpServletRequest JavaDoc request, String JavaDoc defaultValue) {
242         Cookie JavaDoc c = getCookie(name, request);
243         return c == null ? defaultValue : c.getValue();
244     }
245
246     /**
247      * Get the ID of the sessions current property profile
248      *
249      * @param session session
250      * @return property profile ID
251      */

252     public static int getCurrentPropertyProfileId(HttpSession JavaDoc session) {
253         PropertyProfile p = (PropertyProfile) session.getAttribute(Constants.SELECTED_PROFILE);
254         if (p != null) {
255             return p.getResourceId();
256         }
257         return 0;
258     }
259
260     /**
261      * Get the path to the theme the user has selected or default if there is
262      * none
263      *
264      * @param session
265      * @return String
266      */

267     public static String JavaDoc getThemePath(HttpSession JavaDoc session) {
268         try {
269             SessionInfo info = LogonControllerFactory.getInstance().getSessionInfo(session);
270             if (info == null) {
271                 return Property.getProperty(new ProfilePropertyKey(0, null, "ui.theme", UserDatabaseManager.getInstance()
272                                 .getDefaultUserDatabase().getRealm().getResourceId()));
273             } else {
274                 return Property.getProperty(new ProfilePropertyKey(getCurrentPropertyProfileId(session), info.getUser().getPrincipalName(),
275                                 "ui.theme", info.getUser().getRealm().getResourceId()));
276             }
277         } catch (Exception JavaDoc e) {
278         }
279         return "/theme/default";
280     }
281
282     /**
283      * Get if tool tips are enabled for the specified session
284      * @param session
285      * @return boolean
286      */

287     public static boolean getToolTipsEnabled(HttpSession JavaDoc session) {
288         try {
289             SessionInfo info = LogonControllerFactory.getInstance().getSessionInfo(session);
290             if (info == null) {
291                 return Property.getPropertyBoolean(new ProfilePropertyKey(0, null, "ui.toolTips", UserDatabaseManager.getInstance()
292                                 .getDefaultUserDatabase().getRealm().getResourceId()));
293             } else {
294                 return Property.getPropertyBoolean(new ProfilePropertyKey(getCurrentPropertyProfileId(session), info.getUser().getPrincipalName(),
295                                 "ui.toolTips", info.getUser().getRealm().getResourceId()));
296             }
297         } catch (Exception JavaDoc e) {
298         }
299         return true;
300     }
301
302     /**
303      * Add a page intercept listener to the provided session. This will be
304      * invoked on every page request until it is removed. The listener will then
305      * have the oppurtunity to return a forward redirecting the user if some
306      * condition is satisified.
307      *
308      * @param servletSession session to add listener to
309      * @param listener listener to add
310      */

311     @SuppressWarnings JavaDoc("unchecked")
312     public static void addPageInterceptListener(HttpSession JavaDoc servletSession, PageInterceptListener listener) {
313         synchronized (servletSession) {
314             List JavaDoc<PageInterceptListener> pagetInterceptListeners = (List JavaDoc<PageInterceptListener>) servletSession.getAttribute(Constants.PAGE_INTERCEPT_LISTENERS);
315             if (pagetInterceptListeners == null) {
316                 pagetInterceptListeners = new ArrayList JavaDoc<PageInterceptListener>();
317                 servletSession.setAttribute(Constants.PAGE_INTERCEPT_LISTENERS, pagetInterceptListeners);
318             }
319             pagetInterceptListeners.add(listener);
320         }
321     }
322
323     /**
324      * Remove a page intercept listener from the provided session. This listener
325      * will no longer be messaged upon every required
326      *
327      * @param servletSession session to remove listener from
328      * @param listener listener to remove
329      */

330     @SuppressWarnings JavaDoc("unchecked")
331     public static void removePageInterceptListener(HttpSession JavaDoc servletSession, PageInterceptListener listener) {
332         synchronized (servletSession) {
333             List JavaDoc<PageInterceptListener> pagetInterceptListeners = (List JavaDoc<PageInterceptListener>) servletSession.getAttribute(Constants.PAGE_INTERCEPT_LISTENERS);
334             if (pagetInterceptListeners != null) {
335                 pagetInterceptListeners.remove(listener);
336                 if (pagetInterceptListeners.size() == 0) {
337                     servletSession.removeAttribute(Constants.PAGE_INTERCEPT_LISTENERS);
338                 }
339                 PageInterceptListener pil = (PageInterceptListener) servletSession.getAttribute(Constants.PAGE_INTERCEPTED);
340                 if (pil == listener) {
341                     servletSession.removeAttribute(Constants.PAGE_INTERCEPTED);
342                 }
343             }
344         }
345     }
346
347     /**
348      * Get a page intercept listener given its id. <code>null</code> will be
349      * returned if no listener with the given id exists.
350      *
351      * @param servletSession session that contains the listener
352      * @param id listener id
353      * @return listener
354      */

355     @SuppressWarnings JavaDoc("unchecked")
356     public static PageInterceptListener getPageInterceptListenerById(HttpSession JavaDoc servletSession, String JavaDoc id) {
357         synchronized (servletSession) {
358             List JavaDoc<PageInterceptListener> pagetInterceptListeners = (List JavaDoc<PageInterceptListener>) servletSession.getAttribute(Constants.PAGE_INTERCEPT_LISTENERS);
359             if (pagetInterceptListeners != null) {
360
361                 for (PageInterceptListener listener : pagetInterceptListeners) {
362                     if (listener.getId().equals(id)) {
363                         return listener;
364                     }
365                 }
366             }
367         }
368         return null;
369     }
370
371     /**
372      * Convenience method to remove a page intercept listener from the provided
373      * session given its ID. This listener will no longer be messaged upon every
374      * required
375      * @param session
376      * @param id
377      *
378      */

379     public static void removePageInterceptListener(HttpSession JavaDoc session, String JavaDoc id) {
380         PageInterceptListener l = getPageInterceptListenerById(session, id);
381         if (l != null) {
382             removePageInterceptListener(session, l);
383         }
384     }
385
386     /**
387      * Check if there are page intercepts for the current action. If there are a
388      * forward will be returned pointing to which page should be displayed next
389      *
390      * @param action action object
391      * @param mapping action mapping
392      * @param request request object
393      * @param response response object
394      * @return forward
395      * @throws Exception on any error
396      */

397     @SuppressWarnings JavaDoc("unchecked")
398     public static ActionForward checkIntercept(Action action, ActionMapping mapping, HttpServletRequest JavaDoc request,
399                                                HttpServletResponse JavaDoc response) throws Exception JavaDoc {
400
401         // Cannot intercept during Ajax
402
if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
403             return null;
404         }
405         
406         // Cannot intercept during task
407
if(request.getAttribute(TaskHttpServletRequest.ATTR_TASK) != null) {
408             return null;
409         }
410         
411         ActionForward fwd = null;
412         try {
413             List JavaDoc<PageInterceptListener> pagetInterceptListeners = (List JavaDoc<PageInterceptListener>) request.getSession()
414                             .getAttribute(Constants.PAGE_INTERCEPT_LISTENERS);
415             if (pagetInterceptListeners != null) {
416                 PageInterceptListener currentIntercept = (PageInterceptListener) request.getSession()
417                                 .getAttribute(Constants.PAGE_INTERCEPTED);
418                 PageInterceptListener pil = null;
419                 if (currentIntercept != null) {
420                     pil = currentIntercept;
421                     fwd = currentIntercept.checkForForward(action, mapping, request, response);
422                 } else {
423                     for (Iterator JavaDoc i = pagetInterceptListeners.iterator(); fwd == null && i.hasNext();) {
424                         pil = (PageInterceptListener) i.next();
425                         fwd = pil.checkForForward(action, mapping, request, response);
426                     }
427                 }
428                 if (fwd != null) {
429                     if (!pil.isRedirect()) {
430                         request.getSession().setAttribute(Constants.PAGE_INTERCEPTED, pil);
431                     } else {
432                         CoreUtil.removePageInterceptListener(request.getSession(), pil);
433                     }
434                     return fwd;
435                 }
436             }
437             return null;
438         } catch (Exception JavaDoc e) {
439             log.error("Page intercept failed.", e);
440             throw e;
441         }
442     }
443
444     /**
445      * Add a new global message that will be displayed to all users that have
446      * the specified permissions (type
447      * {@link GlobalWarning#USERS_WITH_PERMISSIONS}.
448      *
449      * @param requiredResourceType required resource type
450      * @param requiredPermissions required permissions
451      * @param message message
452      */

453     @SuppressWarnings JavaDoc("unchecked")
454     public static void addGlobalWarning(ResourceType requiredResourceType, Permission[] requiredPermissions,
455                                         BundleActionMessage message) {
456         HttpSession JavaDoc servletSession;
457         for (Iterator JavaDoc i = CoreRequestProcessor.getSessions().entrySet().iterator(); i.hasNext();) {
458             servletSession = (HttpSession JavaDoc) ((Map.Entry JavaDoc) i.next()).getValue();
459             SessionInfo info = LogonControllerFactory.getInstance().getSessionInfo(servletSession);
460             if (info != null) {
461                 try {
462                     if(PolicyDatabaseFactory.getInstance().isPermitted(requiredResourceType, requiredPermissions, info.getUser(), false)) {
463                         addSingleSessionGlobalWarning(servletSession, message);
464                     }
465                 } catch (Exception JavaDoc e) {
466                     log.error("Failed to add global warning. ", e);
467                 }
468             }
469         }
470         List JavaDoc<GlobalWarning> servletContextGlobalWarnings = (List JavaDoc<GlobalWarning>) CoreServlet.getServlet()
471                         .getServletContext()
472                         .getAttribute(Constants.SESSION_GLOBAL_WARNINGS);
473         if (servletContextGlobalWarnings == null) {
474             servletContextGlobalWarnings = new ArrayList JavaDoc<GlobalWarning>();
475         }
476         servletContextGlobalWarnings.add(new GlobalWarning(requiredResourceType, requiredPermissions, message));
477         CoreServlet.getServlet().getServletContext().setAttribute(Constants.SESSION_GLOBAL_WARNINGS, servletContextGlobalWarnings);
478     }
479
480     /**
481      * Add a new global message for types {@link GlobalWarning#SUPER_USER},
482      * {@link GlobalWarning#MANAGEMENT_USERS} or {@link GlobalWarning#ALL_USERS}.
483      *
484      * @param type global warning type
485      * @param message message
486      * @throws IllegalArgumentException if incorrect type
487      * @see GlobalWarning
488      */

489     @SuppressWarnings JavaDoc("unchecked")
490     public static void addMultipleGlobalWarning(int type, BundleActionMessage message) {
491         HttpSession JavaDoc servletSession = null;
492         for (Iterator JavaDoc i = CoreRequestProcessor.getSessions().entrySet().iterator(); i.hasNext();) {
493             servletSession = (HttpSession JavaDoc) ((Map.Entry JavaDoc) i.next()).getValue();
494             SessionInfo info = LogonControllerFactory.getInstance().getSessionInfo(servletSession);
495             if (info != null) {
496                 try {
497                     if ((type == GlobalWarning.SUPER_USER && LogonControllerFactory.getInstance()
498                                     .isAdministrator(info.getUser())) || (type == GlobalWarning.MANAGEMENT_USERS && PolicyDatabaseFactory.getInstance()
499                                     .isAnyAccessRightAllowed(info.getUser(), true, true, false))
500                         || type == GlobalWarning.ALL_USERS) {
501                         addSingleSessionGlobalWarning(servletSession, message);
502                     }
503                 } catch (Exception JavaDoc e) {
504                     log.error("Failed to add global warning.", e);
505                 }
506             }
507         }
508         List JavaDoc<GlobalWarning> servletContextGlabalWarnings = (List JavaDoc<GlobalWarning>) CoreServlet.getServlet()
509                         .getServletContext()
510                         .getAttribute(Constants.SESSION_GLOBAL_WARNINGS);
511         if (servletContextGlabalWarnings == null) {
512             servletContextGlabalWarnings = new ArrayList JavaDoc<GlobalWarning>();
513         }
514         servletContextGlabalWarnings.add(new GlobalWarning(type, message));
515         CoreServlet.getServlet().getServletContext().setAttribute(Constants.SESSION_GLOBAL_WARNINGS, servletContextGlabalWarnings);
516     }
517
518     /**
519      * Add a new global message for type {@link GlobalWarning#SINGLE_SESSION}.
520      *
521      * @param servletSession session to add warning to
522      * @param message message
523      * @throws IllegalArgumentException if incorrect type
524      * @see GlobalWarning
525      */

526     @SuppressWarnings JavaDoc("unchecked")
527     public static void addSingleSessionGlobalWarning(HttpSession JavaDoc servletSession, BundleActionMessage message) {
528         synchronized (servletSession) {
529             SessionInfo info = LogonControllerFactory.getInstance().getSessionInfo(servletSession);
530             if (info != null) {
531                 List JavaDoc<BundleActionMessage> l = (List JavaDoc<BundleActionMessage>) servletSession.getAttribute(Constants.GLOBAL_WARNINGS);
532                 if (l == null) {
533                     l = new ArrayList JavaDoc<BundleActionMessage>();
534                     servletSession.setAttribute(Constants.GLOBAL_WARNINGS, l);
535                 }
536                 BundleActionMessage m = null;
537                 boolean found = false;
538                 for (Iterator JavaDoc<BundleActionMessage> i = l.iterator(); !found && i.hasNext();) {
539                     m = i.next();
540                     if (m.getBundle().equals(message.getBundle()) && m.getKey().equals(message.getKey())) {
541                         found = true;
542                     }
543                 }
544                 if (!found) {
545                     l.add(message);
546                 }
547             }
548         }
549     }
550
551     /**
552      * Remove a global warning givens its message resource key. If a
553      * <code>null</code> servlet session is provided then the global warning
554      * will be removed from all sessions
555      *
556      * @param servletSession session to remove warning from or <code>null</code>
557      * for all sessions
558      * @param key message resource key
559      */

560     public static void removeGlobalWarning(HttpSession JavaDoc servletSession, String JavaDoc key) {
561         if (servletSession == null) {
562             for (Iterator JavaDoc i = CoreRequestProcessor.getSessions().entrySet().iterator(); i.hasNext();) {
563                 servletSession = (HttpSession JavaDoc) ((Map.Entry JavaDoc) i.next()).getValue();
564                 removeGlobalWarning(servletSession, key);
565             }
566             List JavaDoc servletContextGlabalWarnings = (List JavaDoc) CoreServlet.getServlet()
567                             .getServletContext()
568                             .getAttribute(Constants.SESSION_GLOBAL_WARNINGS);
569             if (servletContextGlabalWarnings != null) {
570                 Iterator JavaDoc iter = servletContextGlabalWarnings.iterator();
571                 while (iter.hasNext()) {
572                     GlobalWarning gw = (GlobalWarning) iter.next();
573                     BundleActionMessage element = gw.getMessage();
574                     if (element.getKey().equals(key)) {
575                         servletContextGlabalWarnings.remove(element);
576                         break;
577                     }
578                 }
579             }
580         } else {
581             synchronized (servletSession) {
582                 List JavaDoc l = (List JavaDoc) servletSession.getAttribute(Constants.GLOBAL_WARNINGS);
583                 if (l == null) {
584                     l = new ArrayList JavaDoc();
585                     servletSession.setAttribute(Constants.GLOBAL_WARNINGS, l);
586                 }
587                 for (int i = l.size() - 1; i >= 0; i--) {
588                     BundleActionMessage msg = (BundleActionMessage) l.get(i);
589                     if (msg.getKey().equals(key)) {
590                         l.remove(i);
591                         break;
592                     }
593                 }
594             }
595         }
596     }
597
598     /**
599      * Convenience method to Remove all global warnings with the specified key
600      * from all active sessions
601      *
602      * @param key message resources key of global warning
603      */

604     public static void removeGlobalWarningFromAllSessions(String JavaDoc key) {
605         removeGlobalWarning(null, key);
606     }
607
608     /**
609      * Initialise a
610      *
611      * @param f
612      * @param request
613      *
614      */

615     public static void initCoreForm(CoreForm f, HttpServletRequest JavaDoc request) {
616         f.setReferer(CoreUtil.getReferer(request));
617     }
618
619     /**
620      * @param session
621      * @param agreement
622      */

623     @SuppressWarnings JavaDoc("unchecked")
624     public static void requestLicenseAgreement(HttpSession JavaDoc session, LicenseAgreement agreement) {
625         List JavaDoc<LicenseAgreement> l = (List JavaDoc<LicenseAgreement>) session.getAttribute(Constants.LICENSE_AGREEMENTS);
626         if (l == null) {
627             l = new ArrayList JavaDoc<LicenseAgreement>();
628             session.setAttribute(Constants.LICENSE_AGREEMENTS, l);
629             log.info("Requesting license agreement for " + agreement.getLicenseTextFile().getAbsolutePath());
630             addPageInterceptListener(session, new PageInterceptListener() {
631                 public String JavaDoc getId() {
632                     return "licenseAgreement";
633                 }
634
635                 public boolean isRedirect() {
636                     return true;
637                 }
638
639                 public ActionForward checkForForward(Action action, ActionMapping mapping, HttpServletRequest JavaDoc request,
640                                                      HttpServletResponse JavaDoc response) throws PageInterceptException {
641                     if (!(action instanceof LicenseAgreementDispatchAction)) {
642                         return new ActionForward("/showLicenseAgreement.do", true);
643                     }
644                     return null;
645                 }
646             });
647         }
648         l.add(agreement);
649     }
650
651     /**
652      * @param request
653      * @param warnings
654      */

655     public static void addWarnings(HttpServletRequest JavaDoc request, ActionMessages warnings) {
656         if (warnings == null) {
657             return;
658         }
659         ActionMessages requestWarnings = (ActionMessages) request.getAttribute(Constants.REQ_ATTR_WARNINGS);
660         if (requestWarnings == null) {
661             requestWarnings = new ActionMessages();
662         }
663         requestWarnings.add(warnings);
664         if (requestWarnings.isEmpty()) {
665             request.removeAttribute(Constants.REQ_ATTR_WARNINGS);
666             return;
667         }
668         request.setAttribute(Constants.REQ_ATTR_WARNINGS, requestWarnings);
669     }
670
671     /**
672      * Get the current warnings, creating them if none exists
673      *
674      * @return the warnings that already exist in the request, or a new
675      * ActionMessages object if empty.
676      * @param request The servlet request we are processing
677      */

678     public static ActionMessages getWarnings(HttpServletRequest JavaDoc request) {
679         ActionMessages warnings = (ActionMessages) request.getAttribute(Constants.REQ_ATTR_WARNINGS);
680         if (warnings == null) {
681             warnings = new ActionMessages();
682         }
683         return warnings;
684     }
685
686     /**
687      * Save the specified warnings messages.
688      *
689      * @param request request
690      * @param warnings warnings
691      */

692     public static void saveWarnings(HttpServletRequest JavaDoc request, ActionMessages warnings) {
693         if ((warnings == null) || warnings.isEmpty()) {
694             request.removeAttribute(Constants.REQ_ATTR_WARNINGS);
695             return;
696         }
697         request.setAttribute(Constants.REQ_ATTR_WARNINGS, warnings);
698     }
699
700     /**
701      * @param request
702      * @return String
703      */

704     public static String JavaDoc getReferer(HttpServletRequest JavaDoc request) {
705         String JavaDoc ref = request.getHeader("Referer");
706         if (ref != null) {
707             ref = processRefererString(ref);
708         } else {
709             /*
710              * IE sometimes doesnt send the referer (from javascript for
711              * instance) so we should try using our referer parameter
712              * work-around.
713              */

714             ref = getRequestReferer(request);
715         }
716         return ref;
717     }
718     
719     /**
720      * @param request
721      * @return String
722      */

723     public static String JavaDoc getRequestReferer(HttpServletRequest JavaDoc request) {
724         if (isRefererInRequest(request)) {
725             return processRefererString(request.getParameter("referer"));
726         }
727         return null;
728     }
729
730     /**
731      * @param request
732      * @return boolean
733      */

734     public static boolean isRefererInRequest(HttpServletRequest JavaDoc request) {
735         return request.getParameter("referer") != null;
736     }
737
738     /**
739      * @param redirect
740      * @return String
741      */

742     static String JavaDoc processRefererString(String JavaDoc redirect) {
743         try {
744             URL JavaDoc u = new URL JavaDoc(redirect);
745             String JavaDoc query = u.getQuery();
746             if (query != null && !query.equals("")) {
747                 StringBuffer JavaDoc nq = new StringBuffer JavaDoc();
748                 StringTokenizer JavaDoc t = new StringTokenizer JavaDoc(query, "&");
749                 String JavaDoc parm = null;
750                 while (t.hasMoreTokens()) {
751                     parm = t.nextToken();
752                     if (!parm.startsWith("referer=") && !parm.startsWith("vpnMessage=") && !parm.startsWith("vpnError=")) {
753                         if (nq.length() > 0) {
754                             nq.append("&");
755                         }
756                         nq.append(parm);
757                     }
758                 }
759                 query = nq.length() == 0 ? null : nq.toString();
760             }
761             StringBuffer JavaDoc file = new StringBuffer JavaDoc();
762             if (u.getPath() != null) {
763                 file.append(u.getPath());
764             }
765             if (query != null) {
766                 file.append("?");
767                 file.append(query);
768             }
769             if (u.getRef() != null) {
770                 file.append("#");
771                 file.append(u.getRef());
772             }
773             u = new URL JavaDoc(u.getProtocol(), u.getHost(), u.getPort(), file.toString());
774             return u.toExternalForm();
775         } catch (MalformedURLException JavaDoc mrule) {
776             int idx = redirect.indexOf("?");
777             if (idx != -1) {
778                 String JavaDoc query = redirect.substring(idx + 1);
779                 redirect = redirect.substring(0, idx);
780                 if (query.length() > 0) {
781                     StringBuffer JavaDoc nq = new StringBuffer JavaDoc();
782                     StringTokenizer JavaDoc t = new StringTokenizer JavaDoc(query, "&");
783                     String JavaDoc parm = null;
784                     while (t.hasMoreTokens()) {
785                         parm = t.nextToken();
786                         if (!parm.startsWith("vpnMessage=") && !parm.startsWith("vpnError=")) {
787                             if (nq.length() > 0) {
788                                 nq.append("&");
789                             }
790                             nq.append(parm);
791                         }
792                     }
793                     query = nq.length() == 0 ? null : nq.toString();
794                     if (query != null) {
795                         redirect = redirect + "?" + query;
796                     }
797                 }
798             }
799             return redirect;
800         }
801     }
802     
803     /**
804      * Remove a parameter from a path
805      *
806      * @param path path to remove parameter from
807      * @param name name of parameter
808      * @return path with parameter removed
809      */

810     public static String JavaDoc removeParameterFromPath(String JavaDoc path, String JavaDoc name) {
811         boolean first = true;
812         int idx = path.indexOf("?" + name + "=");
813         if(idx == -1) {
814             first = false;
815             idx = path.indexOf("&" + name + "=");
816         }
817         if(idx != -1) {
818             int eidx = path.indexOf('&', idx + 1);
819             if(eidx == -1) {
820                 path = path.substring(0, idx);
821             }
822             else {
823                 path = path.substring(0, idx) + ( first ? "?" : "&" ) + path.substring(eidx + 1, path.length());
824             }
825         }
826         return path;
827     }
828
829     /**
830      * Add a new parameter to an already encoded request path
831      *
832      * @param path orginal path
833      * @param name new parameter name
834      * @param value new parameter value
835      * @return new path
836      */

837     public static String JavaDoc addParameterToPath(String JavaDoc path, String JavaDoc name, String JavaDoc value) {
838         StringBuffer JavaDoc buf = new StringBuffer JavaDoc(path);
839         int idx = path.indexOf("?");
840         if (idx != -1) {
841             buf.append("&");
842         } else {
843             buf.append("?");
844         }
845         buf.append(name);
846         buf.append("=");
847         buf.append(Util.urlEncode(value));
848         return buf.toString();
849     }
850
851     /**
852      * @param forward
853      * @param name
854      * @param value
855      * @return ActionForward
856      */

857     public static ActionForward addParameterToForward(ActionForward forward, String JavaDoc name, String JavaDoc value) {
858         ActionForward f = new ActionForward(forward);
859         f.setPath(addParameterToPath(forward.getPath(), name, value));
860         return f;
861     }
862
863     /**
864      * @param pageContext
865      */

866     public static void dumpComponentContext(PageContext JavaDoc pageContext) {
867         ComponentContext compContext = (ComponentContext) pageContext.getAttribute(ComponentConstants.COMPONENT_CONTEXT,
868             PageContext.REQUEST_SCOPE);
869         if (log.isInfoEnabled())
870             log.info("Component context dump");
871         for (Iterator JavaDoc e = compContext.getAttributeNames(); e.hasNext();) {
872             String JavaDoc n = (String JavaDoc) e.next();
873             Object JavaDoc value = compContext.getAttribute(n);
874             if (log.isInfoEnabled())
875                 log.info(" " + n + " = " + value);
876         }
877     }
878
879     /**
880      * Get the proxy URL to use for a user.
881      *
882      * @param user user
883      * @param propertyProfile property profile ID (0 for default / global)
884      * @return String
885      * @throws Exception
886      */

887     public static String JavaDoc getProxyURL(User user, int propertyProfile) throws Exception JavaDoc {
888         String JavaDoc type = Property.getProperty(new ProfilePropertyKey(propertyProfile, user.getPrincipalName(), "clientProxy.type", user.getRealm().getResourceId()));
889         if (type.equals("http") || type.equals("https")) {
890             String JavaDoc hostname = Property.getProperty(new ProfilePropertyKey(propertyProfile, user.getPrincipalName(), "clientProxy.hostname", user.getRealm().getResourceId()));
891             if (!hostname.equals("")) {
892                 StringBuffer JavaDoc url = new StringBuffer JavaDoc();
893                 url.append(type);
894                 url.append("://");
895                 
896                 String JavaDoc username = Property.getProperty(new ProfilePropertyKey(propertyProfile, user.getPrincipalName(), "clientProxy.username", user.getRealm().getResourceId()));
897                 String JavaDoc domain = Property.getProperty(new ProfilePropertyKey(propertyProfile, user.getPrincipalName(), "clientProxy.ntlmDomain", user.getRealm().getResourceId()));
898                 String JavaDoc auth = Property.getProperty(new ProfilePropertyKey(propertyProfile, user.getPrincipalName(), "clientProxy.preferredAuthentication", user.getRealm().getResourceId()));
899
900                 if (!username.equals("")) {
901
902                     if (!domain.equals("")) {
903                         url.append(DAVUtilities.encodeURIUserInfo(domain + "\\"));
904                     }
905
906                     url.append(DAVUtilities.encodeURIUserInfo(username));
907                     String JavaDoc password = Property.getProperty(new ProfilePropertyKey(propertyProfile, user.getPrincipalName(), "clientProxy.password", user.getRealm().getResourceId()));
908                     if (!password.equals("")) {
909                         url.append(":");
910                         url.append(DAVUtilities.encodeURIUserInfo(password));
911                     }
912                     url.append("@");
913                 }
914                 url.append(hostname);
915                 int port = Property.getPropertyInt(new ProfilePropertyKey(propertyProfile, user.getPrincipalName(), "clientProxy.port", user.getRealm().getResourceId()));
916                 if (port != 0) {
917                     url.append(":");
918                     url.append(port);
919                 }
920                 url.append("?");
921                 url.append(auth);
922                 return url.toString();
923             }
924         } else if (type.equals("browser")) {
925             String JavaDoc auth = Property.getProperty(new ProfilePropertyKey(propertyProfile, user.getPrincipalName(), "clientProxy.preferredAuthentication", user.getRealm().getResourceId()));
926             return "browser://" + auth;
927         }
928         return null;
929     }
930
931     /**
932      * @param action
933      * @param mapping
934      * @param form
935      * @param request
936      * @param response
937      * @throws Exception
938      */

939     public static void checkNavigationContext(CoreAction action, ActionMapping mapping, ActionForm form,
940                                               HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws Exception JavaDoc {
941         int navigationContext = action.getNavigationContext(mapping, form, request, response);
942         if (!ContextHolder.getContext().isSetupMode()) {
943             SessionInfo info = LogonControllerFactory.getInstance().getSessionInfo(request);
944             if ((navigationContext & info.getNavigationContext()) == 0) {
945                 if ((navigationContext & SessionInfo.MANAGEMENT_CONSOLE_CONTEXT) != 0) {
946                     if(!PolicyDatabaseFactory.getInstance().isAnyAccessRightAllowed(info.getUser(), true, true, false)) {
947                         throw new NoPermissionException("You do not have permission to use the management console.");
948                     }
949                     info.setNavigationContext(SessionInfo.MANAGEMENT_CONSOLE_CONTEXT);
950                     CoreUtil.resetMainNavigation(request.getSession());
951                 } else if ((navigationContext & SessionInfo.USER_CONSOLE_CONTEXT) != 0) {
952                     info.setNavigationContext(SessionInfo.USER_CONSOLE_CONTEXT);
953                     CoreUtil.resetMainNavigation(request.getSession());
954                 } else if ((navigationContext & SessionInfo.HELP_CONTEXT) != 0) {
955                     // do nothing
956
} else {
957                     throw new NoPermissionException("Action does not define any valid navigation contexts that it should be available in.");
958                 }
959             }
960         }
961     }
962
963     /**
964      * @param parameterList
965      * @return Properties
966      * @throws ParseException
967      */

968     public static Properties JavaDoc parseActionParameter(String JavaDoc parameterList) throws ParseException JavaDoc {
969         Properties JavaDoc p = new Properties JavaDoc();
970         String JavaDoc[] properties = parameterList.split(",");
971         for (int i = 0; i < properties.length; i++) {
972             String JavaDoc n = properties[i];
973             int idx = n.indexOf('=');
974             if (idx == -1) {
975                 throw new ParseException JavaDoc("Parameter list in incorrect format. [<name>=<value>[,<name>=<value>] ..]", 0);
976             }
977             String JavaDoc v = n.substring(idx + 1);
978             n = n.substring(0, idx);
979             p.setProperty(n, v);
980         }
981         return p;
982     }
983
984     /**
985      * @param serverInterfaceItem
986      * @return List<CoreSelectableItem>
987      */

988     public static List JavaDoc<CoreSelectableItem> getSelectedItems(List JavaDoc serverInterfaceItem) {
989         List JavaDoc<CoreSelectableItem> l = new ArrayList JavaDoc<CoreSelectableItem>();
990         for (Iterator JavaDoc i = serverInterfaceItem.iterator(); i.hasNext();) {
991             CoreSelectableItem item = (CoreSelectableItem) i.next();
992             if (item.getSelected()) {
993                 l.add(item);
994             }
995         }
996         return l;
997     }
998
999     /**
1000     * @param serverInterfaceItem
1001     * @return List<CoreSelectableItem>
1002     */

1003    public static List JavaDoc<CoreSelectableItem> getDeselectedItems(List JavaDoc serverInterfaceItem) {
1004        List JavaDoc<CoreSelectableItem> l = new ArrayList JavaDoc<CoreSelectableItem>();
1005        for (Iterator JavaDoc i = serverInterfaceItem.iterator(); i.hasNext();) {
1006            CoreSelectableItem item = (CoreSelectableItem) i.next();
1007            if (!item.getSelected()) {
1008                l.add(item);
1009            }
1010        }
1011        return l;
1012    }
1013
1014    /**
1015     * @param items
1016     */

1017    public static void deselectAllItems(List JavaDoc items) {
1018        for (Iterator JavaDoc i = items.iterator(); i.hasNext();) {
1019            CoreSelectableItem item = (CoreSelectableItem) i.next();
1020            item.setSelected(false);
1021        }
1022    }
1023
1024    /**
1025     * @param items
1026     */

1027    public static void selectAllItems(List JavaDoc items) {
1028        for (Iterator JavaDoc i = items.iterator(); i.hasNext();) {
1029            CoreSelectableItem item = (CoreSelectableItem) i.next();
1030            item.setSelected(false);
1031        }
1032    }
1033
1034    /**
1035     * Check whether the session associated in the middle of wizard.
1036     *
1037     * @param session session
1038     * @return in a wizard
1039     */

1040    public static boolean isInWizard(HttpSession JavaDoc session) {
1041        return session.getAttribute(Constants.WIZARD_SEQUENCE) != null;
1042    }
1043
1044    /**
1045     * Reset the main navigation menu so it gets rebuilt upon the next request
1046     *
1047     * @param session
1048     *
1049     */

1050    public static void resetMainNavigation(HttpSession JavaDoc session) {
1051        session.removeAttribute(Constants.MENU_TREE);
1052        session.removeAttribute(Constants.NAV_BAR);
1053    }
1054
1055    /**
1056     * Get if the menu is currently available. This is often used to determine
1057     * if the user is on a page that cannot be safely navigated away from.
1058     *
1059     * @param request
1060     *
1061     * @return menu is available
1062     */

1063    public static boolean isMenuAvailable(HttpServletRequest JavaDoc request) {
1064        return request.getAttribute(Constants.SELECTED_MENU) != null && request.getSession()
1065                        .getAttribute(Constants.PAGE_INTERCEPTED) == null;
1066    }
1067
1068    /**
1069     * @param action
1070     * @param request
1071     */

1072    public static void addRequiredFieldMessage(Action action, HttpServletRequest JavaDoc request) {
1073        ActionMessages mesgs = (ActionMessages) request.getAttribute(Globals.MESSAGE_KEY);
1074        if (mesgs == null) {
1075            mesgs = new ActionMessages();
1076            request.setAttribute(Globals.MESSAGE_KEY, mesgs);
1077        }
1078        mesgs.add(Globals.MESSAGE_KEY, new BundleActionMessage("navigation",
1079                        "info.requiredFieldIndicator",
1080                        "<img SRC=\"" + getThemePath(request.getSession()) + "/images/required.gif" + "\" border=\"0\"/>"));
1081    }
1082
1083    /**
1084     * @param originalPath
1085     * @return String
1086     */

1087    public static String JavaDoc platformPath(String JavaDoc originalPath) {
1088        String JavaDoc p = originalPath.replace("/", File.separator).replace("\\", File.separator);
1089        if (log.isDebugEnabled())
1090            log.debug("Original path of '" + originalPath + "' is '" + p + "' for platform");
1091        return p;
1092    }
1093
1094    /**
1095     * @param f
1096     * @return long
1097     * @throws IOException
1098     */

1099    public static long generateChecksum(File JavaDoc f) throws IOException JavaDoc {
1100        Adler32 JavaDoc alder = new Adler32 JavaDoc();
1101        FileInputStream JavaDoc fin = new FileInputStream JavaDoc(f);
1102        CheckedInputStream JavaDoc in = new CheckedInputStream JavaDoc(fin, alder);
1103        byte[] buf = new byte[32768];
1104        Util.readFullyIntoBuffer(in, buf);
1105        alder = (Adler32 JavaDoc) in.getChecksum();
1106        try {
1107            in.close();
1108        } catch (IOException JavaDoc ex) {
1109        }
1110        try {
1111            fin.close();
1112        } catch (IOException JavaDoc ex1) {
1113        }
1114        return alder.getValue();
1115    }
1116
1117    /**
1118     * @param role
1119     * @param database
1120     * @return User[]
1121     * @throws Exception
1122     */

1123    public static User[] getUsersInRole(Role role, UserDatabase database) throws Exception JavaDoc {
1124        User[] u = database.listAllUsers("*");
1125        List JavaDoc<User> ur = new ArrayList JavaDoc<User>();
1126        for (int i = 0; i < u.length; i++) {
1127            Role[] r = u[i].getRoles();
1128            for (int j = 0; j < r.length; j++) {
1129                if (r[j].getPrincipalName().equals(role.getPrincipalName())) {
1130                    ur.add(u[i]);
1131                    break;
1132                }
1133            }
1134        }
1135        return (User[]) ur.toArray(new User[ur.size()]);
1136    }
1137
1138    /**
1139     * Dump tile attributes to {@link System#err}.
1140     *
1141     * @param pageContext page context from which to get tile.
1142     */

1143    public static void dumpTileScope(PageContext JavaDoc pageContext) {
1144        ComponentContext compContext = (ComponentContext) pageContext.getAttribute(ComponentConstants.COMPONENT_CONTEXT,
1145            PageContext.REQUEST_SCOPE);
1146        System.err.println("Tile attributes");
1147        for (Iterator JavaDoc i = compContext.getAttributeNames(); i.hasNext();) {
1148            String JavaDoc n = (String JavaDoc) i.next();
1149            System.err.println(" " + n + " = " + compContext.getAttribute(n));
1150        }
1151    }
1152
1153    /**
1154     * Get message resources given the ID and the session. <code>null</code>
1155     * will be returned if no such resources exist.
1156     *
1157     * @param session session
1158     * @param key bundle key
1159     * @return resources
1160     */

1161    public static MessageResources getMessageResources(HttpSession JavaDoc session, String JavaDoc key) {
1162        ServletContext JavaDoc context = session.getServletContext();
1163        ModuleConfig moduleConfig = ModuleUtils.getInstance().getModuleConfig("", context);
1164        return (MessageResources) context.getAttribute(key + moduleConfig.getPrefix());
1165    }
1166    
1167    public static String JavaDoc getMessage(HttpSession JavaDoc session, String JavaDoc bundle, String JavaDoc key) {
1168        MessageResources resources = getMessageResources(session, bundle);
1169        Locale JavaDoc locale = (Locale JavaDoc)session.getAttribute(Globals.LOCALE_KEY);
1170        return resources.getMessage(locale, key);
1171    }
1172    
1173    public static String JavaDoc getMessage(SessionInfo session, String JavaDoc bundle, String JavaDoc key) {
1174        return getMessage(session.getHttpSession(), bundle, key);
1175    }
1176    
1177    public static String JavaDoc getMessage(HttpServletRequest JavaDoc request, String JavaDoc bundle, String JavaDoc key) {
1178        return getMessage(request.getSession(), bundle, key);
1179    }
1180
1181    /**
1182     * Adds a new path to the paths search for native libraries. Because
1183     * <i>java.library.path</i> cannot be changed at runtime. This method is a
1184     * workaround that directly changes a private variables in the Sun classes,
1185     * so will probably not work on other JVMs.
1186     *
1187     * @param path path to add
1188     * @throws IOException ioe
1189     */

1190    public static void addLibraryPath(String JavaDoc path) throws IOException JavaDoc {
1191        try {
1192            Field JavaDoc field = ClassLoader JavaDoc.class.getDeclaredField("usr_paths");
1193            field.setAccessible(true);
1194            String JavaDoc[] paths = (String JavaDoc[]) field.get(null);
1195            for (int i = 0; i < paths.length; i++) {
1196                if (path.equals(paths[i])) {
1197                    return;
1198                }
1199            }
1200            String JavaDoc[] tmp = new String JavaDoc[paths.length + 1];
1201            System.arraycopy(paths, 0, tmp, 0, paths.length);
1202            tmp[paths.length] = path;
1203            field.set(null, tmp);
1204        } catch (IllegalAccessException JavaDoc e) {
1205            throw new IOException JavaDoc("Failed to get permissions to set library path");
1206        } catch (NoSuchFieldException JavaDoc e) {
1207            /*
1208             * This will likely happen if not Suns JVM. Just in case it does
1209             * work, we'll set java.library.path
1210             */

1211            System.setProperty("java.library.path", System.getProperty("java.library.path") + File.pathSeparator + path);
1212            log.warn("Failed to set library path using Sun JDK workaround. Just setting java.library.path in case " + "it works. If it doesn't, plugins that use native libraries will probably fail. To fix "
1213                + "this you will have to alter "
1214                + ContextHolder.getContext().getConfDirectory().getAbsolutePath()
1215                + File.separator
1216                + "wrapper.conf to include the additional library path '"
1217                + path
1218                + "'.");
1219        }
1220    }
1221
1222    /**
1223     * Replace all occurences of string <i>token</i> in <i>source</i> with
1224     * <i>value</i>.
1225     *
1226     * @param source source to search for occurences of <i>token</i>
1227     * @param token string to search for
1228     * @param value value to replace occurences of <i>token</i> with
1229     * @return processed string
1230     */

1231    public static String JavaDoc replaceAllTokens(String JavaDoc source, String JavaDoc token, String JavaDoc value) {
1232        return StringUtils.replace(source, token, value);
1233    }
1234
1235    /**
1236     * Add a new upload to the sessions upload manager, creating one if needed.
1237     *
1238     * @param session session
1239     * @param upload upload
1240     * @return id;
1241     */

1242    public static int addUpload(HttpSession JavaDoc session, UploadDetails upload) {
1243        synchronized (session) {
1244            UploadManager mgr = (UploadManager) session.getAttribute(Constants.UPLOAD_MANAGER);
1245            if (mgr == null) {
1246                mgr = new UploadManager();
1247                session.setAttribute(Constants.UPLOAD_MANAGER, mgr);
1248            }
1249            return mgr.addUpload(upload);
1250        }
1251    }
1252
1253    /**
1254     * Remove an upload given its id, removing the upload manager if it is
1255     * empty.
1256     *
1257     * @param session session
1258     * @param uploadId upload id
1259     * @return removed upload details
1260     */

1261    public static UploadDetails removeUpload(HttpSession JavaDoc session, int uploadId) {
1262        UploadManager mgr = (UploadManager) session.getAttribute(Constants.UPLOAD_MANAGER);
1263        if (mgr != null) {
1264            UploadDetails details = mgr.removeUpload(uploadId);
1265            if (mgr.isEmpty()) {
1266                session.removeAttribute(Constants.UPLOAD_MANAGER);
1267            }
1268            return details;
1269        }
1270        return null;
1271    }
1272
1273    /**
1274     * Get an upload given its id. <code>null</code> will be returned if no
1275     * upload exists.
1276     *
1277     * @param session session
1278     * @param id
1279     * @return upload
1280     */

1281    public static UploadDetails getUpload(HttpSession JavaDoc session, int id) {
1282        UploadManager mgr = (UploadManager) session.getAttribute(Constants.UPLOAD_MANAGER);
1283        if (mgr != null) {
1284            return mgr.getUpload(id);
1285        }
1286        return null;
1287    }
1288
1289    /**
1290     * @param clazz
1291     * @param tag
1292     * @return Tag
1293     */

1294    public static Tag JavaDoc getParentTagOfClass(Class JavaDoc clazz, Tag JavaDoc tag) {
1295        while ((tag = tag.getParent()) != null) {
1296            if (tag.getClass().equals(clazz)) {
1297                return tag;
1298            }
1299        }
1300        return null;
1301    }
1302
1303    /**
1304     * Get if a specific authentication module has been configured for use in
1305     * any schemes and is enabled
1306     *
1307     * @param moduleName
1308     * @return module is use
1309     * @throws Exception if authentication schemes cannot be loaded
1310     */

1311    public static boolean isAuthenticationModuleInUse(String JavaDoc moduleName) throws Exception JavaDoc {
1312        List JavaDoc authenticationSchemes = SystemDatabaseFactory.getInstance().getAuthenticationSchemeSequences();
1313        for (Iterator JavaDoc i = authenticationSchemes.iterator(); i.hasNext();) {
1314            AuthenticationScheme seq = (DefaultAuthenticationScheme) i.next();
1315            if (seq.hasModule(moduleName) && seq.getEnabled()) {
1316                return true;
1317            }
1318        }
1319        return false;
1320    }
1321
1322    /**
1323     * Store the provided user interface state name / value pair in a cookie
1324     *
1325     * @param name ui state cookie name
1326     * @param value ui state cookie value
1327     * @param request request
1328     * @param response response
1329     */

1330    public static void storeUIState(String JavaDoc name, String JavaDoc value, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
1331        Cookie JavaDoc c = getCookie(name, request);
1332        if (c != null) {
1333            c.setValue(value);
1334        } else {
1335            c = new Cookie JavaDoc(name, value);
1336        }
1337        c.setMaxAge(-1);
1338        response.addCookie(c);
1339    }
1340
1341    /**
1342     * Get the real request URI from within a tile
1343     *
1344     * @param request request
1345     * @return real request URI
1346     *
1347     */

1348    public static String JavaDoc getRealRequestURI(HttpServletRequest JavaDoc request) {
1349        HttpServletRequest JavaDoc tmpRequest = request;
1350        while (tmpRequest instanceof HttpServletRequestWrapper JavaDoc) {
1351            tmpRequest = (HttpServletRequest JavaDoc) ((HttpServletRequestWrapper JavaDoc) tmpRequest).getRequest();
1352        }
1353        return tmpRequest.getRequestURI();
1354    }
1355
1356    /**
1357     * Get if the request is for a page in the user console.
1358     *
1359     * @param request
1360     * @return boolean in user console
1361     */

1362    public static boolean isInUserConsole(HttpServletRequest JavaDoc request) {
1363        SessionInfo session = (SessionInfo) request.getSession().getAttribute(Constants.SESSION_INFO);
1364        return session != null && session.getNavigationContext() == SessionInfo.USER_CONSOLE_CONTEXT;
1365    }
1366
1367    /**
1368     * Get if the request is for a page in the management console.
1369     *
1370     * @param request
1371     * @return boolean in user console
1372     */

1373    public static boolean isInManagementConsole(HttpServletRequest JavaDoc request) {
1374        SessionInfo session = (SessionInfo) request.getSession().getAttribute(Constants.SESSION_INFO);
1375        return session != null && session.getNavigationContext() == SessionInfo.MANAGEMENT_CONSOLE_CONTEXT;
1376    }
1377
1378    /**
1379     * @param session
1380     * @param propertyName
1381     * @param user
1382     * @return String
1383     */

1384    public static String JavaDoc getUsersProfileProperty(HttpSession JavaDoc session, String JavaDoc propertyName, User user) {
1385        return Property.getProperty(new ProfilePropertyKey(getCurrentPropertyProfileId(session),
1386                        user == null ? null : user.getPrincipalName(), propertyName, user == null ? UserDatabaseManager
1387                                        .getInstance().getDefaultUserDatabase().getRealm().getResourceId() : user
1388                                        .getRealm().getResourceId()));
1389    }
1390
1391    /**
1392     * @param session
1393     * @param propertyName
1394     * @param user
1395     * @return boolean
1396     */

1397    public static boolean getUsersProfilePropertyBoolean(HttpSession JavaDoc session, String JavaDoc propertyName, User user) {
1398        return Property.getPropertyBoolean(new ProfilePropertyKey(getCurrentPropertyProfileId(session),
1399                        user == null ? null : user.getPrincipalName(), propertyName, user == null ? UserDatabaseManager
1400                                        .getInstance().getDefaultUserDatabase().getRealm().getResourceId() : user
1401                                        .getRealm().getResourceId()));
1402    }
1403
1404    /**
1405     * @param session
1406     * @param propertyName
1407     * @param user
1408     * @return int
1409     */

1410    public static int getUsersProfilePropertyInt(HttpSession JavaDoc session, String JavaDoc propertyName, User user) {
1411        return Property.getPropertyInt(new ProfilePropertyKey(getCurrentPropertyProfileId(session),
1412                        user == null ? null : user.getPrincipalName(), propertyName, user == null ? UserDatabaseManager
1413                                        .getInstance().getDefaultUserDatabase().getRealm().getResourceId() : user
1414                                        .getRealm().getResourceId()));
1415    }
1416
1417    /**
1418     * Utility method that requires the auditing plugin to be available that all
1419     * of the constants in the provided class as event codes.
1420     * <p>
1421     * The bundle containing I18n message resource is also required.
1422     * <p>
1423     * Reflection is used to prevent introducing any compile time dependencies on
1424     * the auditing module.
1425     *
1426     * @param bundle bundle containing message resources
1427     * @param clazz class containing event codes
1428     */

1429    public static void updateEventsTable(String JavaDoc bundle, Class JavaDoc clazz) {
1430        Plugin auditingPlugin = PluginType.getPlugin("sslexplorer-enterprise-auditing");
1431        if (auditingPlugin == null) {
1432            if(log.isDebugEnabled())
1433                log.warn("Could not locate auditing plugin. No events codes can be updated.");
1434        } else {
1435            try {
1436                Method JavaDoc m = auditingPlugin.getClass().getMethod("getDatabase", new Class JavaDoc[] {});
1437                Database d = (Database) m.invoke(auditingPlugin, new Object JavaDoc[] {});
1438                m = d.getClass().getMethod("updateEventsTable", new Class JavaDoc[] { String JavaDoc.class, Class JavaDoc.class });
1439                m.invoke(d, new Object JavaDoc[] { bundle, clazz });
1440            } catch (Exception JavaDoc e) {
1441                log.error("Failed to register event codes.", e);
1442            }
1443        }
1444    }
1445
1446    /**
1447     * Clean flow state.
1448     *
1449     * @param request request
1450     */

1451    public static void clearFlow(HttpServletRequest JavaDoc request) {
1452        request.getSession().removeAttribute(Constants.WIZARD_SEQUENCE);
1453        request.getSession().removeAttribute(Constants.SUSPENDED_WIZARD_SEQUENCE);
1454        ResourceStack.popFromEditingStack(request.getSession());
1455        request.getSession().removeAttribute(Constants.EDITING_ITEM);
1456    }
1457    
1458    /**
1459     * Check if a URI string is safe, only allowing relative
1460     * or URI, absolute URI or HTTPS URI. An exception is
1461     * thrown if the uri contains an
1462     *
1463     * @param uri uri to check
1464     * @throws IllegalArgumentException if unsafe
1465     */

1466    public static void checkSafeURI(String JavaDoc uri) {
1467        URI JavaDoc location;
1468        try {
1469            location = new URI JavaDoc(uri);
1470        } catch (URISyntaxException JavaDoc e) {
1471            throw new IllegalArgumentException JavaDoc(uri + " is not safe.");
1472        }
1473        if( location.getScheme() != null && !"http".equalsIgnoreCase(location.getScheme()) &&
1474                !"https".equalsIgnoreCase(location.getScheme()) ) {
1475            throw new IllegalArgumentException JavaDoc(uri + " is not safe.");
1476        }
1477    }
1478    
1479    /**
1480     * Filter a URI string, only allowing relative
1481     * or URI, absolute URI or HTTPS URI.
1482     *
1483     * @param uri uri to filter
1484     * @param replacement replacement URI if filter matches
1485     * @return filtered URI
1486     */

1487    public static String JavaDoc filterSafeURI(String JavaDoc uri, String JavaDoc replacement) {
1488        try {
1489            checkSafeURI(uri);
1490        } catch (IllegalArgumentException JavaDoc e) {
1491            return replacement;
1492        }
1493        return uri;
1494    }
1495
1496
1497    /**
1498     * Get a date formatter appropriate for the logged on users
1499     * profile.
1500     *
1501     * @param request
1502     * @return date formatter
1503     */

1504    public static DateFormat JavaDoc getDateFormat(HttpServletRequest JavaDoc request) {
1505        return getDateFormat(request, null);
1506    }
1507
1508
1509    /**
1510     * Get a date formatter appropriate for the logged on users
1511     * profile.
1512     *
1513     * @param request request
1514     * @param timeFormat time format
1515     * @return date formatter
1516     */

1517    public static DateFormat JavaDoc getDateFormat(HttpServletRequest JavaDoc request, String JavaDoc timeFormat) {
1518        return new SimpleDateFormat JavaDoc(
1519            Property.getProperty(
1520                    new ProfilePropertyKey("ui.dateFormat",
1521                            LogonControllerFactory.getInstance().getSessionInfo(request))) + ( timeFormat == null ? "" : ( " " + timeFormat )) );
1522    }
1523    
1524    /**
1525     * Turns an Exception stacktrace into a String.
1526     * @param t
1527     * @return String representation of the stacktrace.
1528     */

1529    public static String JavaDoc toString(Throwable JavaDoc t) {
1530        StringWriter JavaDoc stringWriter = new StringWriter JavaDoc();
1531        PrintWriter JavaDoc printWriter = new PrintWriter JavaDoc(stringWriter);
1532        t.printStackTrace(printWriter);
1533        return stringWriter.toString();
1534    }
1535}
Popular Tags