1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.ibatis.datasource.unpooled;
17
18 import java.util.Properties;
19
20 import javax.sql.DataSource;
21
22 import org.apache.ibatis.datasource.DataSourceException;
23 import org.apache.ibatis.datasource.DataSourceFactory;
24 import org.apache.ibatis.reflection.MetaObject;
25 import org.apache.ibatis.reflection.SystemMetaObject;
26
27
28
29
30 public class UnpooledDataSourceFactory implements DataSourceFactory {
31
32 private static final String DRIVER_PROPERTY_PREFIX = "driver.";
33 private static final int DRIVER_PROPERTY_PREFIX_LENGTH = DRIVER_PROPERTY_PREFIX.length();
34
35 protected DataSource dataSource;
36
37 public UnpooledDataSourceFactory() {
38 this.dataSource = new UnpooledDataSource();
39 }
40
41 @Override
42 public void setProperties(Properties properties) {
43 Properties driverProperties = new Properties();
44 MetaObject metaDataSource = SystemMetaObject.forObject(dataSource);
45 for (Object key : properties.keySet()) {
46 String propertyName = (String) key;
47 if (propertyName.startsWith(DRIVER_PROPERTY_PREFIX)) {
48 String value = properties.getProperty(propertyName);
49 driverProperties.setProperty(propertyName.substring(DRIVER_PROPERTY_PREFIX_LENGTH), value);
50 } else if (metaDataSource.hasSetter(propertyName)) {
51 String value = (String) properties.get(propertyName);
52 Object convertedValue = convertValue(metaDataSource, propertyName, value);
53 metaDataSource.setValue(propertyName, convertedValue);
54 } else {
55 throw new DataSourceException("Unknown DataSource property: " + propertyName);
56 }
57 }
58 if (driverProperties.size() > 0) {
59 metaDataSource.setValue("driverProperties", driverProperties);
60 }
61 }
62
63 @Override
64 public DataSource getDataSource() {
65 return dataSource;
66 }
67
68 private Object convertValue(MetaObject metaDataSource, String propertyName, String value) {
69 Object convertedValue = value;
70 Class<?> targetType = metaDataSource.getSetterType(propertyName);
71 if (targetType == Integer.class || targetType == int.class) {
72 convertedValue = Integer.valueOf(value);
73 } else if (targetType == Long.class || targetType == long.class) {
74 convertedValue = Long.valueOf(value);
75 } else if (targetType == Boolean.class || targetType == boolean.class) {
76 convertedValue = Boolean.valueOf(value);
77 }
78 return convertedValue;
79 }
80
81 }