001 /*
002 * Copyright 2002-2004 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
005 * use this file except in compliance with the License. You may obtain a copy of
006 * the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
012 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
013 * License for the specific language governing permissions and limitations under
014 * the License.
015 */
016 package org.springframework.richclient.settings.j2seprefs;
017
018 import java.io.IOException;
019 import java.util.prefs.Preferences;
020 import java.util.prefs.PreferencesFactory;
021
022 import org.springframework.richclient.settings.Settings;
023 import org.springframework.richclient.settings.SettingsFactory;
024 import org.springframework.util.Assert;
025 import org.springframework.util.StringUtils;
026
027 /**
028 * Settings factory that uses J2SE Preferences.
029 *
030 * @author Peter De Bruycker
031 */
032 public class PreferencesSettingsFactory implements SettingsFactory {
033 private PreferencesFactory preferencesFactory;
034
035 private String id;
036
037 public String getId() {
038 return id;
039 }
040
041 public void setId(String id) {
042 this.id = id;
043 }
044
045 public PreferencesFactory getPreferencesFactory() {
046 return preferencesFactory;
047 }
048
049 public void setPreferencesFactory(PreferencesFactory preferencesFactory) {
050 this.preferencesFactory = preferencesFactory;
051 }
052
053 private Preferences getForId(Preferences root, String id) {
054 Assert.notNull(root);
055 Preferences result = root;
056 String[] idParts = id.split("\\.");
057 for (int i = 0; i < idParts.length; i++) {
058 result = result.node(idParts[i]);
059 }
060 return result;
061 }
062
063 public Settings createSettings(String name) {
064 Assert.state(StringUtils.hasText(id), "An id must be assigned.");
065 Settings settings = null;
066 if (preferencesFactory == null) {
067 settings = new PreferencesSettings(getForId(Preferences.userRoot(), id).node(name));
068 } else {
069 settings = new PreferencesSettings(getForId(preferencesFactory.userRoot(), id).node(name));
070 }
071
072 try {
073 settings.load();
074 } catch (IOException e) {
075 throw new RuntimeException(e);
076 }
077
078 return settings;
079 }
080
081 }