KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > ivata > groupware > admin > setting > SettingsImpl


1 /*
2  * Copyright (c) 2001 - 2005 ivata limited.
3  * All rights reserved.
4  * -----------------------------------------------------------------------------
5  * ivata groupware may be redistributed under the GNU General Public
6  * License as published by the Free Software Foundation;
7  * version 2 of the License.
8  *
9  * These programs are free software; you can redistribute them and/or
10  * modify them under the terms of the GNU General Public License
11  * as published by the Free Software Foundation; version 2 of the License.
12  *
13  * These programs are distributed in the hope that they will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
16  *
17  * See the GNU General Public License in the file LICENSE.txt for more
18  * details.
19  *
20  * If you would like a copy of the GNU General Public License write to
21  *
22  * Free Software Foundation, Inc.
23  * 59 Temple Place - Suite 330
24  * Boston, MA 02111-1307, USA.
25  *
26  *
27  * To arrange commercial support and licensing, contact ivata at
28  * http://www.ivata.com/contact.jsp
29  * -----------------------------------------------------------------------------
30  * $Log: SettingsImpl.java,v $
31  * Revision 1.4 2005/04/22 09:19:17 colinmacleod
32  * Added better error handling (when
33  * value is null).
34  *
35  * Revision 1.3 2005/04/10 20:08:14 colinmacleod
36  * Added new themes.
37  * Changed id type to String.
38  * Changed i tag to em and b tag to strong.
39  * Improved PicoContainerFactory with NanoContainer scripts.
40  *
41  * Revision 1.2 2005/04/09 17:19:05 colinmacleod
42  * Changed copyright text to GPL v2 explicitly.
43  *
44  * Revision 1.1.1.1 2005/03/10 17:50:38 colinmacleod
45  * Restructured ivata op around Hibernate/PicoContainer.
46  * Renamed ivata groupware.
47  *
48  * Revision 1.5 2004/11/12 18:17:09 colinmacleod
49  * Ordered imports.
50  *
51  * Revision 1.4 2004/11/12 15:56:46 colinmacleod
52  * Removed dependencies on SSLEXT.
53  * Moved Persistence classes to ivata masks.
54  *
55  * Revision 1.3 2004/11/03 15:33:05 colinmacleod
56  * Cosmetic changes.
57  *
58  * Revision 1.2 2004/07/13 19:54:31 colinmacleod
59  * Moved project to POJOs from EJBs.
60  * Applied PicoContainer to services layer (replacing session EJBs).
61  * Applied Hibernate to persistence layer (replacing entity EJBs).
62  * -----------------------------------------------------------------------------
63  */

64 package com.ivata.groupware.admin.setting;
65
66 import java.text.SimpleDateFormat JavaDoc;
67 import java.util.Arrays JavaDoc;
68 import java.util.Iterator JavaDoc;
69 import java.util.Locale JavaDoc;
70 import java.util.Map JavaDoc;
71 import java.util.ResourceBundle JavaDoc;
72
73 import com.ivata.groupware.admin.security.server.SecuritySession;
74 import com.ivata.groupware.admin.security.user.UserDO;
75 import com.ivata.groupware.business.BusinessLogic;
76 import com.ivata.groupware.container.persistence.QueryPersistenceManager;
77 import com.ivata.mask.persistence.FinderException;
78 import com.ivata.mask.persistence.PersistenceSession;
79 import com.ivata.mask.util.StringHandling;
80 import com.ivata.mask.util.SystemException;
81 import com.ivata.mask.validation.ValidationError;
82 import com.ivata.mask.validation.ValidationErrors;
83 import com.ivata.mask.validation.ValidationException;
84
85
86 /**
87  * <p>This class controls/sets the global preferences.</p>
88  *
89  * @since 2001-09-06
90  * @author Colin MacLeod
91  * <a HREF='mailto:colin.macleod@ivata.com'>colin.macleod@ivata.com</a>
92  * @version $Revision: 1.4 $
93  */

94 public class SettingsImpl extends BusinessLogic implements Settings {
95     /**
96      * Persistence manger used to store/retrieve data objects, or retrieve a
97      * new persistence session.
98      */

99     private QueryPersistenceManager persistenceManager;
100
101     /**
102      * Construct a new address book.
103      *
104      * @param persistenceManager used to store objects in db.
105      */

106     public SettingsImpl(final QueryPersistenceManager persistenceManager) {
107         this.persistenceManager = persistenceManager;
108     }
109     /**
110      * <p>
111      * Change the value of an existing setting.
112      * </p>
113      *
114      * @param name the name of the setting to set
115      * @param value new value to be set.
116      * @param user if not <code>null</code>, then the setting for this user
117      * is set, otherwise the general setting is changed.
118      */

119     public void amendSetting(final SecuritySession securitySession,
120             final String JavaDoc name,
121             final Object JavaDoc value,
122             final UserDO user)
123             throws SystemException {
124         PersistenceSession persistenceSession = persistenceManager.openSession(securitySession);
125         try {
126             // type must be the same as the existing one
127
SettingDO generalSetting = (SettingDO) persistenceManager.findInstance(persistenceSession,
128                 "adminSettingByName", new Object JavaDoc[] {name});
129
130             if ((generalSetting.getType() == SettingConstants.DATA_TYPE_INTEGER)
131                     && !(value instanceof Integer JavaDoc)) {
132                 throw new ValidationException(
133                         new ValidationError(
134                                 "errors.setting.type.integer",
135                                 Arrays.asList(new Object JavaDoc[] {
136                                         value.getClass().getName(),
137                                         value
138                                         })));
139             } else if ((generalSetting.getType() == SettingConstants.DATA_TYPE_BOOLEAN)
140                     && !(value instanceof Boolean JavaDoc)) {
141                 new ValidationError(
142                         "errors.setting.type.boolean",
143                         Arrays.asList(new Object JavaDoc[] {
144                                 value.getClass().getName(),
145                                 value
146                                 }));
147             } else if (!(value instanceof String JavaDoc)) {
148                 String JavaDoc className;
149                 if (value == null) {
150                     className = "[None]";
151                 } else {
152                     className = value.getClass().getName();
153                 }
154                 new ValidationError(
155                         "errors.setting.type.string",
156                         Arrays.asList(new Object JavaDoc[] {
157                                 className,
158                                 value
159                                 }));
160             }
161
162             // if there is no user, change the general setting, otherwise find
163
// the user setting and change that
164
if (user == null) {
165                 generalSetting.setValue(value.toString());
166                 persistenceManager.amend(persistenceSession, generalSetting);
167             } else {
168                 try {
169                     SettingDO setting = (SettingDO) persistenceManager.findInstance(persistenceSession,
170                         "adminSettingByNameUserName", new Object JavaDoc[] {name, user.getName()});
171                     setting.setValue(StringHandling.getNotNull(value, null));
172                 } catch (FinderException e) {
173                     // create a new setting
174
SettingDO setting = new SettingDO();
175                     setting.setDescription(generalSetting.getDescription());
176                     setting.setEnabled(generalSetting.isEnabled());
177                     setting.setName(name);
178                     setting.setType(generalSetting.getType());
179                     setting.setUser(user);
180                     setting.setValue(value.toString());
181                     persistenceManager.add(persistenceSession, setting);
182                 }
183
184             }
185         } catch (Exception JavaDoc e) {
186             persistenceSession.cancel();
187             throw new SystemException(e);
188         } finally {
189             persistenceSession.close();
190         }
191     }
192
193     /**
194      * Find a setting with a given name for the user.
195      *
196      * @param name the name of the setting to find
197      * @param user the user who owns this setting, or <code>null</code> if the
198      * setting is shared by all users.
199      * @param value object of class String, Integer or Boolean
200      */

201     private SettingDO findSetting(final SecuritySession securitySession,
202             final String JavaDoc name,
203             final UserDO user)
204             throws SystemException {
205         PersistenceSession persistenceSession = persistenceManager.openSession(securitySession);
206         try {
207
208             SettingDO setting = null;
209
210             // first try to find the user setting - if a user was specified
211
if ((user != null)
212                     && (user.getName() != null)) {
213                 try {
214                     setting = (SettingDO) persistenceManager.findInstance(persistenceSession,
215                         "adminSettingByNameUserName", new Object JavaDoc[] {name, user.getName()});
216                 } catch (FinderException e) {
217                     // ok - we will try to get the general setting
218
}
219             }
220
221             // if the setting is still null, try to find the general setting
222
if (setting == null) {
223                 setting = (SettingDO) persistenceManager.findInstance(persistenceSession,
224                     "adminSettingByName", new Object JavaDoc[] {name});
225             }
226             return setting;
227         } catch (Exception JavaDoc e) {
228             persistenceSession.cancel();
229             if (e instanceof SystemException) {
230                 throw (SystemException) e;
231             }
232             throw new SystemException(e);
233         } finally {
234             persistenceSession.close();
235         }
236     }
237
238     /**
239      * <p>Get a setting of class <code>Boolean</code>.</p>
240      *
241      * @return the setting if set, or null if not
242      * @param name the name of the setting to return the value for
243      * @param userName the user to search for. If null is specified, the
244      * default setting is searched for and returned if found.
245      * @exception SettingsDataTypeException if the setting has any class other
246      * than Boolean
247      * @return a setting of class <code>Boolean</code> for the setting
248      * name provided.
249      * @see #getSetting
250      * @see #getIntegerSetting
251      * @see #getStringSetting
252      * @throws SettingNullException if this setting does not exist.
253      */

254     public final Boolean JavaDoc getBooleanSetting(final SecuritySession session,
255             final String JavaDoc name,
256             final UserDO user) throws SystemException {
257         return (Boolean JavaDoc) getSettingOfType(session, name, user, Boolean JavaDoc.class);
258     }
259     /**
260      * <p>Get a setting of class <code>Integer</code>.</p>
261      *
262      * @exception SettingsDataTypeException if the setting has any class other
263      * than Integer.
264      * @return the setting if set, or null if not
265      * @param name the name of the setting to return the value for.
266      * @param userName the user to search for. If null is specified, the
267      * default setting is searched for and returned if found.
268      * @return a setting of class <code>Integer</code> for the setting
269      * name provided.
270      * @see #getSetting
271      * @see #getStringSetting
272      * @see #getBooleanSetting
273      * @throws SettingNullException if this setting does not exist.
274      */

275     public final Integer JavaDoc getIntegerSetting(final SecuritySession session,
276             final String JavaDoc name,
277             final UserDO user) throws SystemException {
278         return (Integer JavaDoc) getSettingOfType(session, name, user, Integer JavaDoc.class);
279     }
280
281     /**
282      * <p>Get a setting for a given user. The class of the returned object will
283      * depend on the <code>type</code> field of the EJB with this name and can
284      * be one of:</br/>
285      * <ul>
286      * <li><code>Integer</code></li>
287      * <li><code>String</code></li>
288      * <li><code>Boolean</code></li></p>
289      *
290      * @return the setting if set, or null if not
291      * @param name the name of the setting to return the value for
292      * @param userName the user to search for. If null is specified, the
293      * default setting is searched for and returned if found.
294      * @return a setting with the setting name provided. The type of the
295      * returned object depends on the <code>type</code> field of the
296      * setting.
297      * @see #getIntegerSetting
298      * @see #getStringSetting
299      * @see #getBooleanSetting
300      * @throws SettingNullException if this setting does not exist.
301      */

302     public final Object JavaDoc getSetting(final SecuritySession securitySession,
303             final String JavaDoc name,
304             final UserDO userDO) throws SystemException {
305         SettingDO setting = findSetting(securitySession, name, userDO);
306         Object JavaDoc returnObject;
307         // set the type on the basis of the class of the parameter
308
switch (setting.getType()) {
309         case SettingConstants.DATA_TYPE_INTEGER:
310             returnObject = new Integer JavaDoc(setting.getValue());
311             break;
312
313         case SettingConstants.DATA_TYPE_BOOLEAN:
314             returnObject = new Boolean JavaDoc(setting.getValue());
315             break;
316
317             // make the default a string
318
default:
319             returnObject = setting.getValue();
320             break;
321         }
322         return returnObject;
323     }
324
325     /**
326      * Private helper. Get a setting and check it has the type specified.
327      *
328      * @throws SettingsDataTypeException if the type of the setting is not what
329      * we expected.
330      * @throws SystemException see {@link #getSetting getSetting}.
331      */

332     private Object JavaDoc getSettingOfType(final SecuritySession session,
333             final String JavaDoc name,
334             final UserDO user,
335             final Class JavaDoc settingType)
336             throws SettingsDataTypeException,
337             SystemException {
338         Object JavaDoc oTest = getSetting(session, name, user);
339         if ((oTest != null) &&
340                 (!oTest.getClass().getName().equals(settingType.getName()))) {
341                 throw new SettingsDataTypeException("Setting '"
342                         + name
343                         + "' has class '"
344                         + oTest.getClass().getName()
345                         + "', expected '"
346                         + settingType.getName()
347                         + "'.");
348         }
349         return oTest;
350     }
351
352     /**
353      * <p>Get the type of a setting</p>
354      * @param name the name of the setting
355      * @return one of the static fields of <code>SettingConstants</code>
356      * @throws SettingNullException if this setting does not exist.
357      */

358     public final int getSettingType(final SecuritySession securitySession,
359             final String JavaDoc name) throws SystemException {
360         PersistenceSession persistenceSession = persistenceManager.openSession(securitySession);
361         try {
362             return ((SettingDO) persistenceManager.findInstance(persistenceSession, "adminSettingName",
363                 new Object JavaDoc[] {name})).getType();
364         } catch (Exception JavaDoc e) {
365             persistenceSession.cancel();
366             throw new SystemException(e);
367         } finally {
368             persistenceSession.close();
369         }
370     }
371
372     /**
373      * <p>Get a setting of class String.</p>
374      *
375      * @return the setting if set, or null if not
376      * @param name the name of the setting to return the value for
377      * @param userName the user to search for. If null is specified, the
378      * default setting is searched for and returned if found.
379      * @exception SettingsDataTypeException if the setting has any class other
380      * than String
381      * @return a setting of class <code>String</code> for the setting
382      * name provided.
383      * @see #getSetting
384      * @see #getIntegerSetting
385      * @see #getBooleanSetting
386      * @throws SettingNullException if this setting does not exist.
387      */

388     public final String JavaDoc getStringSetting(final SecuritySession session,
389             final String JavaDoc name,
390             final UserDO user) throws SystemException {
391         return (String JavaDoc) getSettingOfType(session, name, user, String JavaDoc.class);
392     }
393     /**
394      * <p>
395      * Find out whether or not a setting is enabled.
396      * </p>
397      *
398      * @param securitySession valid security session.
399      * @param name name of the setting to check.
400      * @return <code>true</code> if the setting exists and is enabled.
401      * @throws SystemException if it don't work out in some way :-)
402      */

403     public boolean isSettingEnabled(final SecuritySession securitySession,
404             final String JavaDoc
405             name)
406             throws SystemException {
407         PersistenceSession persistenceSession = persistenceManager.openSession(securitySession);
408         try {
409             SettingDO setting = (SettingDO) persistenceManager.findInstance(persistenceSession,
410                     "adminSettingByName", new Object JavaDoc[] {name});
411             return setting.isEnabled();
412         } catch (FinderException e) {
413             return false;
414         } catch (Exception JavaDoc e) {
415             persistenceSession.cancel();
416             throw new SystemException(e);
417         } finally {
418             persistenceSession.close();
419         }
420     }
421
422     /**
423      * <p>
424      * Revert a user setting back to the general value.
425      * </p>
426      *
427      * @param name the name of the setting to revert
428      * @param user the setting for this user is reverted
429      */

430     public void revertSetting(final SecuritySession securitySession,
431             final String JavaDoc name,
432             final UserDO user)
433             throws SystemException {
434         assert(user != null);
435
436         PersistenceSession persistenceSession = persistenceManager.openSession(securitySession);
437         try {
438             SettingDO setting = (SettingDO) persistenceManager.findInstance(persistenceSession,
439                 "adminSettingByNameUserName", new Object JavaDoc[] {name, user.getName()});
440             persistenceManager.remove(persistenceSession, setting);
441         } catch (FinderException e) {
442             // that's ok - the default value will already be used
443
} catch (Exception JavaDoc e) {
444             persistenceSession.cancel();
445             throw new SystemException(e);
446         } finally {
447             persistenceSession.close();
448         }
449     }
450
451     /**
452      * <p>Confirm all of the settings passed are correct.</p>
453      *
454      * @param settings a <code>Map</code> with setting names as keys and setting
455      * values as values
456      * @param the <code>Locale</code> to get localised error messages
457      * @param settingType one of the constants in <code>SettingConstants</code>:
458      * <code>SETTING_USER</code> or <code>SETTING_SYSTEM</code>
459      * @return a collection of validation errors if any of the settings contains
460      * invalid value.
461      *
462      * @ejb.interface-method
463      * view-type="both"
464      */

465     public ValidationErrors validate(final SecuritySession session,
466             final Map JavaDoc settings,
467             final Locale JavaDoc locale,
468             final int settingType) throws SystemException {
469         ResourceBundle JavaDoc resources = ResourceBundle.getBundle("com.ivata.groupware.admin.ApplicationResources", locale);
470         ValidationErrors errors = new ValidationErrors();
471
472         String JavaDoc settingAreaString = "";
473         if (settingType == SettingConstants.SETTING_SYSTEM) {
474             settingAreaString = resources.getString("setting.system");
475         } else if (settingType == SettingConstants.SETTING_USER) {
476             settingAreaString = resources.getString("setting.user");
477         }
478
479         // go through all the passed settings and check the ones that need to be
480
// validated
481
String JavaDoc currentName = "";
482         Integer JavaDoc valueInteger;
483         String JavaDoc valueString;
484         Boolean JavaDoc valueBoolean;
485
486         for (Iterator JavaDoc i = settings.keySet().iterator(); i.hasNext(); ) {
487             currentName = (String JavaDoc) i.next();
488
489             // required email string settings
490
if (currentName.equals("emailHost") ||
491                 currentName.equals("emailHostSmtp") ||
492                 currentName.equals("emailFolderInbox") ||
493                 currentName.equals("emailFolderSent") ||
494                 currentName.equals("emailFolderTrash") ||
495                 currentName.equals("emailFolderDrafts")) {
496
497                 if (StringHandling.isNullOrEmpty((String JavaDoc) settings.get(currentName))) {
498                     errors.add(new ValidationError(
499                             "errors.setting.required",
500                             Arrays.asList(new String JavaDoc[] {settingAreaString,
501                                     resources.getString("setting.field."
502                                             + currentName)})));
503                 }
504
505             // email port
506
} else if (currentName.equals("emailPort")) {
507                 valueInteger = (Integer JavaDoc) settings.get(currentName);
508                 if (valueInteger.intValue() < 1 || valueInteger.intValue() > 65535) {
509                     errors.add(new ValidationError(
510                             "errors.setting.range",
511                             Arrays.asList(new String JavaDoc[] {settingAreaString,
512                                     resources.getString("setting.field."
513                                             + currentName),
514                                             "1",
515                                             "65535"})));
516
517                 }
518
519             // library integer settings
520
} else if (currentName.equals("libraryHome") ||
521                 currentName.equals("libraryRecent") ||
522                 currentName.equals("libraryCommentSpacer")) {
523
524                 valueInteger = (Integer JavaDoc) settings.get(currentName);
525                 if (valueInteger.intValue() < 1) {
526                     errors.add(new ValidationError(
527                             "errors.setting.greaterThan",
528                             Arrays.asList(new String JavaDoc[] {settingAreaString,
529                                 resources.getString("setting.field."
530                                         + currentName),
531                                         "0"})));
532
533                 }
534
535
536             // date formats
537
} else if (currentName.equals("i18nDateInputDisplay") ||
538                         currentName.equals("i18nDateLong") ||
539                         currentName.equals("i18nDateLongDay") ||
540                         currentName.equals("i18nDateLongYear") ||
541                         currentName.equals("i18nDateShort") ||
542                         currentName.equals("i18nDateShortYear") ||
543                         currentName.equals("i18nDateWeekDay") ||
544                         currentName.equals("i18nDateShortToday") ||
545                         currentName.equals("i18nDateShortYesterday") ||
546                         currentName.equals("i18nDateThisAfternoon") ||
547                         currentName.equals("i18nDateThisMorning") ||
548                         currentName.equals("i18nDateThisEvening") ||
549                         currentName.equals("i18nDateYesterdayMorning") ||
550                         currentName.equals("i18nDateYesterdayAfternoon") ||
551                         currentName.equals("i18nDateYesterdayEvening")) {
552
553                 // the validation of date formats
554
try {
555                     SimpleDateFormat JavaDoc testDateFormat = new SimpleDateFormat JavaDoc((String JavaDoc) settings.get(currentName));
556                 } catch (IllegalArgumentException JavaDoc e) {
557                     errors.add(new ValidationError(
558                             "errors.setting.date",
559                             Arrays.asList(new String JavaDoc[] {settingAreaString,
560                                     resources.getString("setting.field."
561                                             + currentName)})));
562                 }
563
564             //time formats
565
} else if (currentName.equals("i18nTimeInputDisplay") ||
566                         currentName.equals("i18nTimeLong") ||
567                         currentName.equals("i18nTimeShort")) {
568
569                 // the validation of time formats
570
try {
571                     SimpleDateFormat JavaDoc testDateFormat = new SimpleDateFormat JavaDoc((String JavaDoc) settings.get(currentName));
572                 } catch (IllegalArgumentException JavaDoc e) {
573                     errors.add(new ValidationError(
574                             "errors.setting.time",
575                             Arrays.asList(new String JavaDoc[] {settingAreaString,
576                                     resources.getString("setting.field."
577                                             + currentName)})));
578                 }
579
580
581             }
582
583         }
584         return errors;
585     }
586 }
587
Popular Tags