001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.dbcp2;
018
019import java.io.ByteArrayInputStream;
020import java.io.IOException;
021import java.nio.charset.StandardCharsets;
022import java.sql.Connection;
023import java.sql.SQLException;
024import java.time.Duration;
025import java.util.ArrayList;
026import java.util.Arrays;
027import java.util.Enumeration;
028import java.util.Hashtable;
029import java.util.LinkedHashMap;
030import java.util.List;
031import java.util.Locale;
032import java.util.Map;
033import java.util.Objects;
034import java.util.Optional;
035import java.util.Properties;
036import java.util.StringTokenizer;
037import java.util.function.Consumer;
038import java.util.function.Function;
039
040import javax.naming.Context;
041import javax.naming.Name;
042import javax.naming.RefAddr;
043import javax.naming.Reference;
044import javax.naming.spi.ObjectFactory;
045
046import org.apache.commons.logging.Log;
047import org.apache.commons.logging.LogFactory;
048import org.apache.commons.pool2.impl.BaseObjectPoolConfig;
049import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
050
051/**
052 * JNDI object factory that creates an instance of {@code BasicDataSource} that has been configured based on the
053 * {@code RefAddr} values of the specified {@code Reference}, which must match the names and data types of the
054 * {@code BasicDataSource} bean properties with the following exceptions:
055 * <ul>
056 * <li>{@code connectionInitSqls} must be passed to this factory as a single String using semicolon to delimit the
057 * statements whereas {@code BasicDataSource} requires a collection of Strings.</li>
058 * </ul>
059 *
060 * @since 2.0
061 */
062public class BasicDataSourceFactory implements ObjectFactory {
063
064    private static final Log log = LogFactory.getLog(BasicDataSourceFactory.class);
065
066    private static final String PROP_DEFAULT_AUTO_COMMIT = "defaultAutoCommit";
067    private static final String PROP_DEFAULT_READ_ONLY = "defaultReadOnly";
068    private static final String PROP_DEFAULT_TRANSACTION_ISOLATION = "defaultTransactionIsolation";
069    private static final String PROP_DEFAULT_CATALOG = "defaultCatalog";
070    private static final String PROP_DEFAULT_SCHEMA = "defaultSchema";
071    private static final String PROP_CACHE_STATE = "cacheState";
072    private static final String PROP_DRIVER_CLASS_NAME = "driverClassName";
073    private static final String PROP_LIFO = "lifo";
074    private static final String PROP_MAX_TOTAL = "maxTotal";
075    private static final String PROP_MAX_IDLE = "maxIdle";
076    private static final String PROP_MIN_IDLE = "minIdle";
077    private static final String PROP_INITIAL_SIZE = "initialSize";
078    private static final String PROP_MAX_WAIT_MILLIS = "maxWaitMillis";
079    private static final String PROP_TEST_ON_CREATE = "testOnCreate";
080    private static final String PROP_TEST_ON_BORROW = "testOnBorrow";
081    private static final String PROP_TEST_ON_RETURN = "testOnReturn";
082    private static final String PROP_TIME_BETWEEN_EVICTION_RUNS_MILLIS = "timeBetweenEvictionRunsMillis";
083    private static final String PROP_NUM_TESTS_PER_EVICTION_RUN = "numTestsPerEvictionRun";
084    private static final String PROP_MIN_EVICTABLE_IDLE_TIME_MILLIS = "minEvictableIdleTimeMillis";
085    private static final String PROP_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS = "softMinEvictableIdleTimeMillis";
086    private static final String PROP_EVICTION_POLICY_CLASS_NAME = "evictionPolicyClassName";
087    private static final String PROP_TEST_WHILE_IDLE = "testWhileIdle";
088    private static final String PROP_PASSWORD = Constants.KEY_PASSWORD;
089    private static final String PROP_URL = "url";
090    private static final String PROP_USER_NAME = "username";
091    private static final String PROP_VALIDATION_QUERY = "validationQuery";
092    private static final String PROP_VALIDATION_QUERY_TIMEOUT = "validationQueryTimeout";
093    private static final String PROP_JMX_NAME = "jmxName";
094    private static final String PROP_REGISTER_CONNECTION_MBEAN = "registerConnectionMBean";
095    private static final String PROP_CONNECTION_FACTORY_CLASS_NAME = "connectionFactoryClassName";
096
097    /**
098     * The property name for connectionInitSqls. The associated value String must be of the form [query;]*
099     */
100    private static final String PROP_CONNECTION_INIT_SQLS = "connectionInitSqls";
101    private static final String PROP_ACCESS_TO_UNDERLYING_CONNECTION_ALLOWED = "accessToUnderlyingConnectionAllowed";
102    private static final String PROP_REMOVE_ABANDONED_ON_BORROW = "removeAbandonedOnBorrow";
103    private static final String PROP_REMOVE_ABANDONED_ON_MAINTENANCE = "removeAbandonedOnMaintenance";
104    private static final String PROP_REMOVE_ABANDONED_TIMEOUT = "removeAbandonedTimeout";
105    private static final String PROP_LOG_ABANDONED = "logAbandoned";
106    private static final String PROP_ABANDONED_USAGE_TRACKING = "abandonedUsageTracking";
107    private static final String PROP_POOL_PREPARED_STATEMENTS = "poolPreparedStatements";
108    private static final String PROP_CLEAR_STATEMENT_POOL_ON_RETURN = "clearStatementPoolOnReturn";
109    private static final String PROP_MAX_OPEN_PREPARED_STATEMENTS = "maxOpenPreparedStatements";
110    private static final String PROP_CONNECTION_PROPERTIES = "connectionProperties";
111    private static final String PROP_MAX_CONN_LIFETIME_MILLIS = "maxConnLifetimeMillis";
112    private static final String PROP_LOG_EXPIRED_CONNECTIONS = "logExpiredConnections";
113    private static final String PROP_ROLLBACK_ON_RETURN = "rollbackOnReturn";
114    private static final String PROP_ENABLE_AUTO_COMMIT_ON_RETURN = "enableAutoCommitOnReturn";
115    private static final String PROP_DEFAULT_QUERY_TIMEOUT = "defaultQueryTimeout";
116    private static final String PROP_FAST_FAIL_VALIDATION = "fastFailValidation";
117
118    /**
119     * Value string must be of the form [STATE_CODE,]*
120     */
121    private static final String PROP_DISCONNECTION_SQL_CODES = "disconnectionSqlCodes";
122
123    /*
124     * Block with obsolete properties from DBCP 1.x. Warn users that these are ignored and they should use the 2.x
125     * properties.
126     */
127    private static final String NUPROP_MAX_ACTIVE = "maxActive";
128    private static final String NUPROP_REMOVE_ABANDONED = "removeAbandoned";
129    private static final String NUPROP_MAXWAIT = "maxWait";
130
131    /*
132     * Block with properties expected in a DataSource This props will not be listed as ignored - we know that they may
133     * appear in Resource, and not listing them as ignored.
134     */
135    private static final String SILENT_PROP_FACTORY = "factory";
136    private static final String SILENT_PROP_SCOPE = "scope";
137    private static final String SILENT_PROP_SINGLETON = "singleton";
138    private static final String SILENT_PROP_AUTH = "auth";
139
140    private static final List<String> ALL_PROPERTY_NAMES = Arrays.asList(PROP_DEFAULT_AUTO_COMMIT, PROP_DEFAULT_READ_ONLY,
141            PROP_DEFAULT_TRANSACTION_ISOLATION, PROP_DEFAULT_CATALOG, PROP_DEFAULT_SCHEMA, PROP_CACHE_STATE,
142            PROP_DRIVER_CLASS_NAME, PROP_LIFO, PROP_MAX_TOTAL, PROP_MAX_IDLE, PROP_MIN_IDLE, PROP_INITIAL_SIZE,
143            PROP_MAX_WAIT_MILLIS, PROP_TEST_ON_CREATE, PROP_TEST_ON_BORROW, PROP_TEST_ON_RETURN,
144            PROP_TIME_BETWEEN_EVICTION_RUNS_MILLIS, PROP_NUM_TESTS_PER_EVICTION_RUN, PROP_MIN_EVICTABLE_IDLE_TIME_MILLIS,
145            PROP_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS, PROP_EVICTION_POLICY_CLASS_NAME, PROP_TEST_WHILE_IDLE, PROP_PASSWORD,
146            PROP_URL, PROP_USER_NAME, PROP_VALIDATION_QUERY, PROP_VALIDATION_QUERY_TIMEOUT, PROP_CONNECTION_INIT_SQLS,
147            PROP_ACCESS_TO_UNDERLYING_CONNECTION_ALLOWED, PROP_REMOVE_ABANDONED_ON_BORROW, PROP_REMOVE_ABANDONED_ON_MAINTENANCE,
148            PROP_REMOVE_ABANDONED_TIMEOUT, PROP_LOG_ABANDONED, PROP_ABANDONED_USAGE_TRACKING, PROP_POOL_PREPARED_STATEMENTS,
149            PROP_CLEAR_STATEMENT_POOL_ON_RETURN,
150            PROP_MAX_OPEN_PREPARED_STATEMENTS, PROP_CONNECTION_PROPERTIES, PROP_MAX_CONN_LIFETIME_MILLIS,
151            PROP_LOG_EXPIRED_CONNECTIONS, PROP_ROLLBACK_ON_RETURN, PROP_ENABLE_AUTO_COMMIT_ON_RETURN,
152            PROP_DEFAULT_QUERY_TIMEOUT, PROP_FAST_FAIL_VALIDATION, PROP_DISCONNECTION_SQL_CODES, PROP_JMX_NAME,
153            PROP_REGISTER_CONNECTION_MBEAN, PROP_CONNECTION_FACTORY_CLASS_NAME);
154
155    /**
156     * Obsolete properties from DBCP 1.x. with warning strings suggesting new properties. LinkedHashMap will guarantee
157     * that properties will be listed to output in order of insertion into map.
158     */
159    private static final Map<String, String> NUPROP_WARNTEXT = new LinkedHashMap<>();
160
161    static {
162        NUPROP_WARNTEXT.put(NUPROP_MAX_ACTIVE,
163                "Property " + NUPROP_MAX_ACTIVE + " is not used in DBCP2, use " + PROP_MAX_TOTAL + " instead. "
164                        + PROP_MAX_TOTAL + " default value is " + GenericObjectPoolConfig.DEFAULT_MAX_TOTAL + ".");
165        NUPROP_WARNTEXT.put(NUPROP_REMOVE_ABANDONED,
166                "Property " + NUPROP_REMOVE_ABANDONED + " is not used in DBCP2," + " use one or both of "
167                        + PROP_REMOVE_ABANDONED_ON_BORROW + " or " + PROP_REMOVE_ABANDONED_ON_MAINTENANCE + " instead. "
168                        + "Both have default value set to false.");
169        NUPROP_WARNTEXT.put(NUPROP_MAXWAIT,
170                "Property " + NUPROP_MAXWAIT + " is not used in DBCP2" + " , use " + PROP_MAX_WAIT_MILLIS + " instead. "
171                        + PROP_MAX_WAIT_MILLIS + " default value is " + BaseObjectPoolConfig.DEFAULT_MAX_WAIT
172                        + ".");
173    }
174
175    /**
176     * Silent Properties. These properties will not be listed as ignored - we know that they may appear in JDBC Resource
177     * references, and we will not list them as ignored.
178     */
179    private static final List<String> SILENT_PROPERTIES = new ArrayList<>();
180
181    static {
182        SILENT_PROPERTIES.add(SILENT_PROP_FACTORY);
183        SILENT_PROPERTIES.add(SILENT_PROP_SCOPE);
184        SILENT_PROPERTIES.add(SILENT_PROP_SINGLETON);
185        SILENT_PROPERTIES.add(SILENT_PROP_AUTH);
186
187    }
188
189    private static <V> void accept(final Properties properties, final String name, final Function<String, V> parser, final Consumer<V> consumer) {
190        getOptional(properties, name).ifPresent(v -> consumer.accept(parser.apply(v)));
191    }
192
193    private static void acceptBoolean(final Properties properties, final String name, final Consumer<Boolean> consumer) {
194        accept(properties, name, Boolean::parseBoolean, consumer);
195    }
196
197    private static void acceptDurationOfMillis(final Properties properties, final String name, final Consumer<Duration> consumer) {
198        accept(properties, name, s -> Duration.ofMillis(Long.parseLong(s)), consumer);
199    }
200
201    private static void acceptDurationOfSeconds(final Properties properties, final String name, final Consumer<Duration> consumer) {
202        accept(properties, name, s -> Duration.ofSeconds(Long.parseLong(s)), consumer);
203    }
204
205    private static void acceptInt(final Properties properties, final String name, final Consumer<Integer> consumer) {
206        accept(properties, name, Integer::parseInt, consumer);
207    }
208
209    private static void acceptString(final Properties properties, final String name, final Consumer<String> consumer) {
210        accept(properties, name, Function.identity(), consumer);
211    }
212
213    /**
214     * Creates and configures a {@link BasicDataSource} instance based on the given properties.
215     *
216     * @param properties
217     *            The data source configuration properties.
218     * @return A new a {@link BasicDataSource} instance based on the given properties.
219     * @throws SQLException
220     *             Thrown when an error occurs creating the data source.
221     */
222    public static BasicDataSource createDataSource(final Properties properties) throws SQLException {
223        final BasicDataSource dataSource = new BasicDataSource();
224        acceptBoolean(properties, PROP_DEFAULT_AUTO_COMMIT, dataSource::setDefaultAutoCommit);
225        acceptBoolean(properties, PROP_DEFAULT_READ_ONLY, dataSource::setDefaultReadOnly);
226
227        getOptional(properties, PROP_DEFAULT_TRANSACTION_ISOLATION).ifPresent(value -> {
228            value = value.toUpperCase(Locale.ROOT);
229            int level = PoolableConnectionFactory.UNKNOWN_TRANSACTION_ISOLATION;
230            if ("NONE".equals(value)) {
231                level = Connection.TRANSACTION_NONE;
232            } else if ("READ_COMMITTED".equals(value)) {
233                level = Connection.TRANSACTION_READ_COMMITTED;
234            } else if ("READ_UNCOMMITTED".equals(value)) {
235                level = Connection.TRANSACTION_READ_UNCOMMITTED;
236            } else if ("REPEATABLE_READ".equals(value)) {
237                level = Connection.TRANSACTION_REPEATABLE_READ;
238            } else if ("SERIALIZABLE".equals(value)) {
239                level = Connection.TRANSACTION_SERIALIZABLE;
240            } else {
241                try {
242                    level = Integer.parseInt(value);
243                } catch (final NumberFormatException e) {
244                    System.err.println("Could not parse defaultTransactionIsolation: " + value);
245                    System.err.println("WARNING: defaultTransactionIsolation not set");
246                    System.err.println("using default value of database driver");
247                    level = PoolableConnectionFactory.UNKNOWN_TRANSACTION_ISOLATION;
248                }
249            }
250            dataSource.setDefaultTransactionIsolation(level);
251        });
252
253        acceptString(properties, PROP_DEFAULT_SCHEMA, dataSource::setDefaultSchema);
254        acceptString(properties, PROP_DEFAULT_CATALOG, dataSource::setDefaultCatalog);
255        acceptBoolean(properties, PROP_CACHE_STATE, dataSource::setCacheState);
256        acceptString(properties, PROP_DRIVER_CLASS_NAME, dataSource::setDriverClassName);
257        acceptBoolean(properties, PROP_LIFO, dataSource::setLifo);
258        acceptInt(properties, PROP_MAX_TOTAL, dataSource::setMaxTotal);
259        acceptInt(properties, PROP_MAX_IDLE, dataSource::setMaxIdle);
260        acceptInt(properties, PROP_MIN_IDLE, dataSource::setMinIdle);
261        acceptInt(properties, PROP_INITIAL_SIZE, dataSource::setInitialSize);
262        acceptDurationOfMillis(properties, PROP_MAX_WAIT_MILLIS, dataSource::setMaxWait);
263        acceptBoolean(properties, PROP_TEST_ON_CREATE, dataSource::setTestOnCreate);
264        acceptBoolean(properties, PROP_TEST_ON_BORROW, dataSource::setTestOnBorrow);
265        acceptBoolean(properties, PROP_TEST_ON_RETURN, dataSource::setTestOnReturn);
266        acceptDurationOfMillis(properties, PROP_TIME_BETWEEN_EVICTION_RUNS_MILLIS, dataSource::setDurationBetweenEvictionRuns);
267        acceptInt(properties, PROP_NUM_TESTS_PER_EVICTION_RUN, dataSource::setNumTestsPerEvictionRun);
268        acceptDurationOfMillis(properties, PROP_MIN_EVICTABLE_IDLE_TIME_MILLIS, dataSource::setMinEvictableIdle);
269        acceptDurationOfMillis(properties, PROP_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS, dataSource::setSoftMinEvictableIdle);
270        acceptString(properties, PROP_EVICTION_POLICY_CLASS_NAME, dataSource::setEvictionPolicyClassName);
271        acceptBoolean(properties, PROP_TEST_WHILE_IDLE, dataSource::setTestWhileIdle);
272        acceptString(properties, PROP_PASSWORD, dataSource::setPassword);
273        acceptString(properties, PROP_URL, dataSource::setUrl);
274        acceptString(properties, PROP_USER_NAME, dataSource::setUsername);
275        acceptString(properties, PROP_VALIDATION_QUERY, dataSource::setValidationQuery);
276        acceptDurationOfSeconds(properties, PROP_VALIDATION_QUERY_TIMEOUT, dataSource::setValidationQueryTimeout);
277        acceptBoolean(properties, PROP_ACCESS_TO_UNDERLYING_CONNECTION_ALLOWED, dataSource::setAccessToUnderlyingConnectionAllowed);
278        acceptBoolean(properties, PROP_REMOVE_ABANDONED_ON_BORROW, dataSource::setRemoveAbandonedOnBorrow);
279        acceptBoolean(properties, PROP_REMOVE_ABANDONED_ON_MAINTENANCE, dataSource::setRemoveAbandonedOnMaintenance);
280        acceptDurationOfSeconds(properties, PROP_REMOVE_ABANDONED_TIMEOUT, dataSource::setRemoveAbandonedTimeout);
281        acceptBoolean(properties, PROP_LOG_ABANDONED, dataSource::setLogAbandoned);
282        acceptBoolean(properties, PROP_ABANDONED_USAGE_TRACKING, dataSource::setAbandonedUsageTracking);
283        acceptBoolean(properties, PROP_POOL_PREPARED_STATEMENTS, dataSource::setPoolPreparedStatements);
284        acceptBoolean(properties, PROP_CLEAR_STATEMENT_POOL_ON_RETURN, dataSource::setClearStatementPoolOnReturn);
285        acceptInt(properties, PROP_MAX_OPEN_PREPARED_STATEMENTS, dataSource::setMaxOpenPreparedStatements);
286        getOptional(properties, PROP_CONNECTION_INIT_SQLS).ifPresent(v -> dataSource.setConnectionInitSqls(parseList(v, ';')));
287
288        final String value = properties.getProperty(PROP_CONNECTION_PROPERTIES);
289        if (value != null) {
290            for (final Object key : getProperties(value).keySet()) {
291                final String propertyName = Objects.toString(key, null);
292                dataSource.addConnectionProperty(propertyName, getProperties(value).getProperty(propertyName));
293            }
294        }
295
296        acceptDurationOfMillis(properties, PROP_MAX_CONN_LIFETIME_MILLIS, dataSource::setMaxConn);
297        acceptBoolean(properties, PROP_LOG_EXPIRED_CONNECTIONS, dataSource::setLogExpiredConnections);
298        acceptString(properties, PROP_JMX_NAME, dataSource::setJmxName);
299        acceptBoolean(properties, PROP_REGISTER_CONNECTION_MBEAN, dataSource::setRegisterConnectionMBean);
300        acceptBoolean(properties, PROP_ENABLE_AUTO_COMMIT_ON_RETURN, dataSource::setAutoCommitOnReturn);
301        acceptBoolean(properties, PROP_ROLLBACK_ON_RETURN, dataSource::setRollbackOnReturn);
302        acceptDurationOfSeconds(properties, PROP_DEFAULT_QUERY_TIMEOUT, dataSource::setDefaultQueryTimeout);
303        acceptBoolean(properties, PROP_FAST_FAIL_VALIDATION, dataSource::setFastFailValidation);
304        getOptional(properties, PROP_DISCONNECTION_SQL_CODES).ifPresent(v -> dataSource.setDisconnectionSqlCodes(parseList(v, ',')));
305        acceptString(properties, PROP_CONNECTION_FACTORY_CLASS_NAME, dataSource::setConnectionFactoryClassName);
306
307        // DBCP-215
308        // Trick to make sure that initialSize connections are created
309        if (dataSource.getInitialSize() > 0) {
310            dataSource.getLogWriter();
311        }
312
313        // Return the configured DataSource instance
314        return dataSource;
315    }
316
317    private static Optional<String> getOptional(final Properties properties, final String name) {
318        return Optional.ofNullable(properties.getProperty(name));
319    }
320
321    /**
322     * Parse properties from the string. Format of the string must be [propertyName=property;]*
323     *
324     * @param propText The source text
325     * @return Properties A new Properties instance
326     * @throws SQLException When a paring exception occurs
327     */
328    private static Properties getProperties(final String propText) throws SQLException {
329        final Properties p = new Properties();
330        if (propText != null) {
331            try {
332                p.load(new ByteArrayInputStream(propText.replace(';', '\n').getBytes(StandardCharsets.ISO_8859_1)));
333            } catch (final IOException e) {
334                throw new SQLException(propText, e);
335            }
336        }
337        return p;
338    }
339
340    /**
341     * Parses list of property values from a delimited string
342     *
343     * @param value
344     *            delimited list of values
345     * @param delimiter
346     *            character used to separate values in the list
347     * @return String Collection of values
348     */
349    private static List<String> parseList(final String value, final char delimiter) {
350        final StringTokenizer tokenizer = new StringTokenizer(value, Character.toString(delimiter));
351        final List<String> tokens = new ArrayList<>(tokenizer.countTokens());
352        while (tokenizer.hasMoreTokens()) {
353            tokens.add(tokenizer.nextToken());
354        }
355        return tokens;
356    }
357
358    /**
359     * Creates and return a new {@code BasicDataSource} instance. If no instance can be created, return
360     * {@code null} instead.
361     *
362     * @param obj
363     *            The possibly null object containing location or reference information that can be used in creating an
364     *            object
365     * @param name
366     *            The name of this object relative to {@code nameCtx}
367     * @param nameCtx
368     *            The context relative to which the {@code name} parameter is specified, or {@code null} if
369     *            {@code name} is relative to the default initial context
370     * @param environment
371     *            The possibly null environment that is used in creating this object
372     *
373     * @throws SQLException
374     *             if an exception occurs creating the instance
375     */
376    @Override
377    public Object getObjectInstance(final Object obj, final Name name, final Context nameCtx,
378            final Hashtable<?, ?> environment) throws SQLException {
379
380        // We only know how to deal with {@code javax.naming.Reference}s
381        // that specify a class name of "javax.sql.DataSource"
382        if (obj == null || !(obj instanceof Reference)) {
383            return null;
384        }
385        final Reference ref = (Reference) obj;
386        if (!"javax.sql.DataSource".equals(ref.getClassName())) {
387            return null;
388        }
389
390        // Check property names and log warnings about obsolete and / or unknown properties
391        final List<String> warnMessages = new ArrayList<>();
392        final List<String> infoMessages = new ArrayList<>();
393        validatePropertyNames(ref, name, warnMessages, infoMessages);
394        warnMessages.forEach(log::warn);
395        infoMessages.forEach(log::info);
396
397        final Properties properties = new Properties();
398        ALL_PROPERTY_NAMES.forEach(propertyName -> {
399            final RefAddr ra = ref.get(propertyName);
400            if (ra != null) {
401                properties.setProperty(propertyName, Objects.toString(ra.getContent(), null));
402            }
403        });
404
405        return createDataSource(properties);
406    }
407
408    /**
409     * Collects warnings and info messages. Warnings are generated when an obsolete property is set. Unknown properties
410     * generate info messages.
411     *
412     * @param ref
413     *            Reference to check properties of
414     * @param name
415     *            Name provided to getObject
416     * @param warnMessages
417     *            container for warning messages
418     * @param infoMessages
419     *            container for info messages
420     */
421    private void validatePropertyNames(final Reference ref, final Name name, final List<String> warnMessages,
422            final List<String> infoMessages) {
423        final String nameString = name != null ? "Name = " + name.toString() + " " : "";
424        NUPROP_WARNTEXT.forEach((propertyName, value) -> {
425            final RefAddr ra = ref.get(propertyName);
426            if (ra != null && !ALL_PROPERTY_NAMES.contains(ra.getType())) {
427                final StringBuilder stringBuilder = new StringBuilder(nameString);
428                final String propertyValue = Objects.toString(ra.getContent(), null);
429                stringBuilder.append(value).append(" You have set value of \"").append(propertyValue).append("\" for \"").append(propertyName)
430                        .append("\" property, which is being ignored.");
431                warnMessages.add(stringBuilder.toString());
432            }
433        });
434
435        final Enumeration<RefAddr> allRefAddrs = ref.getAll();
436        while (allRefAddrs.hasMoreElements()) {
437            final RefAddr ra = allRefAddrs.nextElement();
438            final String propertyName = ra.getType();
439            // If property name is not in the properties list, we haven't warned on it
440            // and it is not in the "silent" list, tell user we are ignoring it.
441            if (!(ALL_PROPERTY_NAMES.contains(propertyName) || NUPROP_WARNTEXT.containsKey(propertyName) || SILENT_PROPERTIES.contains(propertyName))) {
442                final String propertyValue = Objects.toString(ra.getContent(), null);
443                final StringBuilder stringBuilder = new StringBuilder(nameString);
444                stringBuilder.append("Ignoring unknown property: ").append("value of \"").append(propertyValue).append("\" for \"").append(propertyName)
445                        .append("\" property");
446                infoMessages.add(stringBuilder.toString());
447            }
448        }
449    }
450}