1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.tomcat.dbcp.dbcp2.datasources;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.RefAddr;
import javax.naming.Reference;
import javax.naming.spi.ObjectFactory;
import org.apache.tomcat.dbcp.dbcp2.ListException;
import org.apache.tomcat.dbcp.dbcp2.Utils;
/**
* A JNDI ObjectFactory which creates {@link SharedPoolDataSource}s or {@link PerUserPoolDataSource}s
*
* @since 2.0
*/
abstract class InstanceKeyDataSourceFactory implements ObjectFactory {
private static final Map<String, InstanceKeyDataSource> INSTANCE_MAP = new ConcurrentHashMap<>();
/**
* Closes all pools associated with this class.
*
* @throws ListException
* a {@link ListException} containing all exceptions thrown by {@link InstanceKeyDataSource#close()}
* @see InstanceKeyDataSource#close()
* @since 2.4.0 throws a {@link ListException} instead of, in 2.3.0 and before, the first exception thrown by
* {@link InstanceKeyDataSource#close()}.
*/
public static void closeAll() throws ListException {
// Get iterator to loop over all instances of this data source.
final List<Throwable> exceptionList = new ArrayList<>(INSTANCE_MAP.size());
INSTANCE_MAP.entrySet().forEach(entry -> {
// Bullet-proof to avoid anything else but problems from InstanceKeyDataSource#close().
if (entry != null) {
final InstanceKeyDataSource value = entry.getValue();
Utils.close(value, exceptionList::add);
}
});
INSTANCE_MAP.clear();
if (!exceptionList.isEmpty()) {
throw new ListException("Could not close all InstanceKeyDataSource instances.", exceptionList);
}
}
/**
* Deserializes the provided byte array to create an object.
*
* @param data
* Data to deserialize to create the configuration parameter.
*
* @return The Object created by deserializing the data.
* @throws ClassNotFoundException
* If a class cannot be found during the deserialization of a configuration parameter.
* @throws IOException
* If an I/O error occurs during the deserialization of a configuration parameter.
*/
protected static final Object deserialize(final byte[] data) throws IOException, ClassNotFoundException {
ObjectInputStream in = null;
try {
in = new ObjectInputStream(new ByteArrayInputStream(data));
return in.readObject();
} finally {
Utils.closeQuietly(in);
}
}
static synchronized String registerNewInstance(final InstanceKeyDataSource ds) {
int max = 0;
for (final String s : INSTANCE_MAP.keySet()) {
if (s != null) {
try {
max = Math.max(max, Integer.parseInt(s));
} catch (final NumberFormatException ignored) {
// no sweat, ignore those keys
}
}
}
final String instanceKey = String.valueOf(max + 1);
// Put a placeholder here for now, so other instances will not
// take our key. We will replace with a pool when ready.
INSTANCE_MAP.put(instanceKey, ds);
return instanceKey;
}
static void removeInstance(final String key) {
if (key != null) {
INSTANCE_MAP.remove(key);
}
}
private Boolean booleanValueOf(final RefAddr refAddr) {
return Boolean.valueOf(toString(refAddr));
}
/**
* Creates an instance of the subclass and sets any properties contained in the Reference.
*
* @param ref
* The properties to be set on the created DataSource
*
* @return A configured DataSource of the appropriate type.
* @throws ClassNotFoundException
* If a class cannot be found during the deserialization of a configuration parameter.
* @throws IOException
* If an I/O error occurs during the deserialization of a configuration parameter.
*/
protected abstract InstanceKeyDataSource getNewInstance(Reference ref) throws IOException, ClassNotFoundException;
/**
* Implements ObjectFactory to create an instance of SharedPoolDataSource or PerUserPoolDataSource
*/
@Override
public Object getObjectInstance(final Object refObj, final Name name, final Context context,
final Hashtable<?, ?> env) throws IOException, ClassNotFoundException {
// The spec says to return null if we can't create an instance
// of the reference
Object obj = null;
if (refObj instanceof Reference) {
final Reference ref = (Reference) refObj;
if (isCorrectClass(ref.getClassName())) {
final RefAddr refAddr = ref.get("instanceKey");
if (hasContent(refAddr)) {
// object was bound to JNDI via Referenceable API.
obj = INSTANCE_MAP.get(refAddr.getContent());
} else {
// Tomcat JNDI creates a Reference out of server.xml
// <ResourceParam> configuration and passes it to an
// instance of the factory given in server.xml.
String key = null;
if (name != null) {
key = name.toString();
obj = INSTANCE_MAP.get(key);
}
if (obj == null) {
final InstanceKeyDataSource ds = getNewInstance(ref);
setCommonProperties(ref, ds);
obj = ds;
if (key != null) {
INSTANCE_MAP.put(key, ds);
}
}
}
}
}
return obj;
}
private boolean hasContent(final RefAddr refAddr) {
return refAddr != null && refAddr.getContent() != null;
}
/**
* Tests if className is the value returned from getClass().getName().toString().
*
* @param className
* The class name to test.
*
* @return true if and only if className is the value returned from getClass().getName().toString()
*/
protected abstract boolean isCorrectClass(String className);
boolean parseBoolean(final RefAddr refAddr) {
return Boolean.parseBoolean(toString(refAddr));
}
int parseInt(final RefAddr refAddr) {
return Integer.parseInt(toString(refAddr));
}
long parseLong(final RefAddr refAddr) {
return Long.parseLong(toString(refAddr));
}
private void setCommonProperties(final Reference ref, final InstanceKeyDataSource ikds)
throws IOException, ClassNotFoundException {
RefAddr refAddr = ref.get("dataSourceName");
if (hasContent(refAddr)) {
ikds.setDataSourceName(toString(refAddr));
}
refAddr = ref.get("description");
if (hasContent(refAddr)) {
ikds.setDescription(toString(refAddr));
}
refAddr = ref.get("jndiEnvironment");
if (hasContent(refAddr)) {
final byte[] serialized = (byte[]) refAddr.getContent();
ikds.setJndiEnvironment((Properties) deserialize(serialized));
}
refAddr = ref.get("loginTimeout");
if (hasContent(refAddr)) {
ikds.setLoginTimeout(toDurationFromSeconds(refAddr));
}
// Pool properties
refAddr = ref.get("blockWhenExhausted");
if (hasContent(refAddr)) {
ikds.setDefaultBlockWhenExhausted(parseBoolean(refAddr));
}
refAddr = ref.get("evictionPolicyClassName");
if (hasContent(refAddr)) {
ikds.setDefaultEvictionPolicyClassName(toString(refAddr));
}
// Pool properties
refAddr = ref.get("lifo");
if (hasContent(refAddr)) {
ikds.setDefaultLifo(parseBoolean(refAddr));
}
refAddr = ref.get("maxIdlePerKey");
if (hasContent(refAddr)) {
ikds.setDefaultMaxIdle(parseInt(refAddr));
}
refAddr = ref.get("maxTotalPerKey");
if (hasContent(refAddr)) {
ikds.setDefaultMaxTotal(parseInt(refAddr));
}
refAddr = ref.get("maxWaitMillis");
if (hasContent(refAddr)) {
ikds.setDefaultMaxWait(toDurationFromMillis(refAddr));
}
refAddr = ref.get("minEvictableIdleTimeMillis");
if (hasContent(refAddr)) {
ikds.setDefaultMinEvictableIdle(toDurationFromMillis(refAddr));
}
refAddr = ref.get("minIdlePerKey");
if (hasContent(refAddr)) {
ikds.setDefaultMinIdle(parseInt(refAddr));
}
refAddr = ref.get("numTestsPerEvictionRun");
if (hasContent(refAddr)) {
ikds.setDefaultNumTestsPerEvictionRun(parseInt(refAddr));
}
refAddr = ref.get("softMinEvictableIdleTimeMillis");
if (hasContent(refAddr)) {
ikds.setDefaultSoftMinEvictableIdle(toDurationFromMillis(refAddr));
}
refAddr = ref.get("testOnCreate");
if (hasContent(refAddr)) {
ikds.setDefaultTestOnCreate(parseBoolean(refAddr));
}
refAddr = ref.get("testOnBorrow");
if (hasContent(refAddr)) {
ikds.setDefaultTestOnBorrow(parseBoolean(refAddr));
}
refAddr = ref.get("testOnReturn");
if (hasContent(refAddr)) {
ikds.setDefaultTestOnReturn(parseBoolean(refAddr));
}
refAddr = ref.get("testWhileIdle");
if (hasContent(refAddr)) {
ikds.setDefaultTestWhileIdle(parseBoolean(refAddr));
}
refAddr = ref.get("timeBetweenEvictionRunsMillis");
if (hasContent(refAddr)) {
ikds.setDefaultDurationBetweenEvictionRuns(toDurationFromMillis(refAddr));
}
// Connection factory properties
refAddr = ref.get("validationQuery");
if (hasContent(refAddr)) {
ikds.setValidationQuery(toString(refAddr));
}
refAddr = ref.get("validationQueryTimeout");
if (hasContent(refAddr)) {
ikds.setValidationQueryTimeout(toDurationFromSeconds(refAddr));
}
refAddr = ref.get("rollbackAfterValidation");
if (hasContent(refAddr)) {
ikds.setRollbackAfterValidation(parseBoolean(refAddr));
}
refAddr = ref.get("maxConnLifetimeMillis");
if (hasContent(refAddr)) {
ikds.setMaxConnLifetime(toDurationFromMillis(refAddr));
}
// Connection properties
refAddr = ref.get("defaultAutoCommit");
if (hasContent(refAddr)) {
ikds.setDefaultAutoCommit(booleanValueOf(refAddr));
}
refAddr = ref.get("defaultTransactionIsolation");
if (hasContent(refAddr)) {
ikds.setDefaultTransactionIsolation(parseInt(refAddr));
}
refAddr = ref.get("defaultReadOnly");
if (hasContent(refAddr)) {
ikds.setDefaultReadOnly(booleanValueOf(refAddr));
}
}
private Duration toDurationFromMillis(final RefAddr refAddr) {
return Duration.ofMillis(parseLong(refAddr));
}
private Duration toDurationFromSeconds(final RefAddr refAddr) {
return Duration.ofSeconds(parseInt(refAddr));
}
String toString(final RefAddr refAddr) {
return refAddr.getContent().toString();
}
}
|