001 /*
002 * Copyright 2002-2006 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.jdbc;
017
018 import java.io.IOException;
019 import java.util.Map;
020
021 import javax.sql.DataSource;
022
023 import org.springframework.beans.factory.InitializingBean;
024 import org.springframework.dao.IncorrectResultSizeDataAccessException;
025 import org.springframework.jdbc.core.JdbcTemplate;
026 import org.springframework.richclient.settings.Settings;
027 import org.springframework.richclient.settings.SettingsException;
028 import org.springframework.richclient.settings.SettingsFactory;
029 import org.springframework.util.Assert;
030
031 /**
032 *
033 * @author Peter De Bruycker
034 */
035 public class JdbcSettingsFactory implements SettingsFactory, InitializingBean {
036 private DataSource dataSource;
037 private UserNameProvider userNameProvider;
038
039 public JdbcSettingsFactory() {
040 }
041
042 public void setDataSource( DataSource dataSource ) {
043 this.dataSource = dataSource;
044 }
045
046 public DataSource getDataSource() {
047 return dataSource;
048 }
049
050 /**
051 * TODO: somehow make the key unique by adding a user name or login or something
052 */
053 public Settings createSettings( String key ) throws SettingsException {
054 try {
055 JdbcTemplate template = new JdbcTemplate( dataSource );
056 Map result = template.queryForMap( "SELECT * FROM SETTINGS WHERE KEY=? AND USER=?", new Object[] { key,
057 userNameProvider.getUser() } );
058
059 JdbcSettings settings = new JdbcSettings( dataSource, userNameProvider.getUser(), (Integer) result
060 .get( "ID" ), key );
061 settings.load();
062 return settings;
063 } catch( IncorrectResultSizeDataAccessException e ) {
064 return new JdbcSettings( dataSource, userNameProvider.getUser(), null, key );
065 } catch( IOException e ) {
066 throw new SettingsException( "Unable to create settings with name " + key, e );
067 }
068 }
069
070 public void setUserNameProvider( UserNameProvider userNameProvider ) {
071 this.userNameProvider = userNameProvider;
072 }
073
074 public UserNameProvider getUserNameProvider() {
075 return userNameProvider;
076 }
077
078 public void afterPropertiesSet() throws Exception {
079 Assert.notNull( userNameProvider, "UserNameProvider must be set" );
080 Assert.notNull( dataSource, "DataSource must be set" );
081 }
082 }