JdbcUtils.java 14.7 KB
Newer Older
1
/*
2 3
 * Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0,
 * and the EPL 1.0 (http://h2database.com/html/license.html).
4 5 6 7
 * Initial Developer: H2 Group
 */
package org.h2.util;

8 9 10 11 12 13
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
14 15 16 17 18
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
19 20
import java.util.ArrayList;
import java.util.HashSet;
21 22 23
import java.util.Properties;
import javax.naming.Context;
import javax.sql.DataSource;
24
import org.h2.api.CustomDataTypesHandler;
25 26 27
import org.h2.api.ErrorCode;
import org.h2.api.JavaObjectSerializer;
import org.h2.engine.SysProperties;
28
import org.h2.message.DbException;
29 30
import org.h2.store.DataHandler;
import org.h2.util.Utils.ClassFactory;
31 32 33 34 35

/**
 * This is a utility class with JDBC helper functions.
 */
public class JdbcUtils {
Thomas Mueller's avatar
Thomas Mueller committed
36

37 38 39 40
    /**
     * The serializer to use.
     */
    public static JavaObjectSerializer serializer;
Thomas Mueller's avatar
Thomas Mueller committed
41

42 43 44 45 46
    /**
     * Custom data types handler to use.
     */
    public static CustomDataTypesHandler customDataTypesHandler;

47 48 49 50 51
    private static final String[] DRIVERS = {
        "h2:", "org.h2.Driver",
        "Cache:", "com.intersys.jdbc.CacheDriver",
        "daffodilDB://", "in.co.daffodil.db.rmi.RmiDaffodilDBDriver",
        "daffodil", "in.co.daffodil.db.jdbc.DaffodilDBDriver",
52
        "db2:", "com.ibm.db2.jcc.DB2Driver",
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
        "derby:net:", "org.apache.derby.jdbc.ClientDriver",
        "derby://", "org.apache.derby.jdbc.ClientDriver",
        "derby:", "org.apache.derby.jdbc.EmbeddedDriver",
        "FrontBase:", "com.frontbase.jdbc.FBJDriver",
        "firebirdsql:", "org.firebirdsql.jdbc.FBDriver",
        "hsqldb:", "org.hsqldb.jdbcDriver",
        "informix-sqli:", "com.informix.jdbc.IfxDriver",
        "jtds:", "net.sourceforge.jtds.jdbc.Driver",
        "microsoft:", "com.microsoft.jdbc.sqlserver.SQLServerDriver",
        "mimer:", "com.mimer.jdbc.Driver",
        "mysql:", "com.mysql.jdbc.Driver",
        "odbc:", "sun.jdbc.odbc.JdbcOdbcDriver",
        "oracle:", "oracle.jdbc.driver.OracleDriver",
        "pervasive:", "com.pervasive.jdbc.v2.Driver",
        "pointbase:micro:", "com.pointbase.me.jdbc.jdbcDriver",
        "pointbase:", "com.pointbase.jdbc.jdbcUniversalDriver",
        "postgresql:", "org.postgresql.Driver",
        "sybase:", "com.sybase.jdbc3.jdbc.SybDriver",
        "sqlserver:", "com.microsoft.sqlserver.jdbc.SQLServerDriver",
        "teradata:", "com.ncr.teradata.TeraDriver",
    };
Thomas Mueller's avatar
Thomas Mueller committed
74

75 76
    private static boolean allowAllClasses;
    private static HashSet<String> allowedClassNames;
77

78 79 80 81
    /**
     *  In order to manage more than one class loader
     */
    private static ArrayList<ClassFactory> userClassFactories =
82
            new ArrayList<>();
83 84

    private static String[] allowedClassNamePrefixes;
Thomas Mueller's avatar
Thomas Mueller committed
85

86 87 88 89
    private JdbcUtils() {
        // utility class
    }

90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
    /**
     * Add a class factory in order to manage more than one class loader.
     *
     * @param classFactory An object that implements ClassFactory
     */
    public static void addClassFactory(ClassFactory classFactory) {
        getUserClassFactories().add(classFactory);
    }

    /**
     * Remove a class factory
     *
     * @param classFactory Already inserted class factory instance
     */
    public static void removeClassFactory(ClassFactory classFactory) {
        getUserClassFactories().remove(classFactory);
    }

    private static ArrayList<ClassFactory> getUserClassFactories() {
        if (userClassFactories == null) {
            // initially, it is empty
            // but Apache Tomcat may clear the fields as well
112
            userClassFactories = new ArrayList<>();
113 114 115 116 117 118 119 120 121 122 123 124 125
        }
        return userClassFactories;
    }

    static {
        String clazz = SysProperties.JAVA_OBJECT_SERIALIZER;
        if (clazz != null) {
            try {
                serializer = (JavaObjectSerializer) loadUserClass(clazz).newInstance();
            } catch (Exception e) {
                throw DbException.convert(e);
            }
        }
126 127 128 129

        String customTypeHandlerClass = SysProperties.CUSTOM_DATA_TYPES_HANDLER;
        if (customTypeHandlerClass != null) {
            try {
130 131
                customDataTypesHandler = (CustomDataTypesHandler)
                        loadUserClass(customTypeHandlerClass).newInstance();
132 133 134 135
            } catch (Exception e) {
                throw DbException.convert(e);
            }
        }
136
    }
Thomas Mueller's avatar
Thomas Mueller committed
137

138 139 140 141 142 143 144 145
    /**
     * Load a class, but check if it is allowed to load this class first. To
     * perform access rights checking, the system property h2.allowedClasses
     * needs to be set to a list of class file name prefixes.
     *
     * @param className the name of the class
     * @return the class object
     */
S.Vladykin's avatar
S.Vladykin committed
146 147
    @SuppressWarnings("unchecked")
    public static <Z> Class<Z> loadUserClass(String className) {
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
        if (allowedClassNames == null) {
            // initialize the static fields
            String s = SysProperties.ALLOWED_CLASSES;
            ArrayList<String> prefixes = New.arrayList();
            boolean allowAll = false;
            HashSet<String> classNames = New.hashSet();
            for (String p : StringUtils.arraySplit(s, ',', true)) {
                if (p.equals("*")) {
                    allowAll = true;
                } else if (p.endsWith("*")) {
                    prefixes.add(p.substring(0, p.length() - 1));
                } else {
                    classNames.add(p);
                }
            }
            allowedClassNamePrefixes = new String[prefixes.size()];
            prefixes.toArray(allowedClassNamePrefixes);
            allowAllClasses = allowAll;
            allowedClassNames = classNames;
        }
        if (!allowAllClasses && !allowedClassNames.contains(className)) {
            boolean allowed = false;
            for (String s : allowedClassNamePrefixes) {
                if (className.startsWith(s)) {
                    allowed = true;
                }
            }
            if (!allowed) {
                throw DbException.get(
                        ErrorCode.ACCESS_DENIED_TO_CLASS_1, className);
            }
        }
        // Use provided class factory first.
        for (ClassFactory classFactory : getUserClassFactories()) {
            if (classFactory.match(className)) {
                try {
                    Class<?> userClass = classFactory.loadClass(className);
                    if (!(userClass == null)) {
S.Vladykin's avatar
S.Vladykin committed
186
                        return (Class<Z>) userClass;
187 188 189 190 191 192 193 194 195
                    }
                } catch (Exception e) {
                    throw DbException.get(
                            ErrorCode.CLASS_NOT_FOUND_1, e, className);
                }
            }
        }
        // Use local ClassLoader
        try {
S.Vladykin's avatar
S.Vladykin committed
196
            return (Class<Z>) Class.forName(className);
197 198
        } catch (ClassNotFoundException e) {
            try {
S.Vladykin's avatar
S.Vladykin committed
199
                return (Class<Z>) Class.forName(
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
                        className, true,
                        Thread.currentThread().getContextClassLoader());
            } catch (Exception e2) {
                throw DbException.get(
                        ErrorCode.CLASS_NOT_FOUND_1, e, className);
            }
        } catch (NoClassDefFoundError e) {
            throw DbException.get(
                    ErrorCode.CLASS_NOT_FOUND_1, e, className);
        } catch (Error e) {
            // UnsupportedClassVersionError
            throw DbException.get(
                    ErrorCode.GENERAL_ERROR_1, e, className);
        }
    }

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
    /**
     * Close a statement without throwing an exception.
     *
     * @param stat the statement or null
     */
    public static void closeSilently(Statement stat) {
        if (stat != null) {
            try {
                stat.close();
            } catch (SQLException e) {
                // ignore
            }
        }
    }

    /**
     * Close a connection without throwing an exception.
     *
     * @param conn the connection or null
     */
    public static void closeSilently(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                // ignore
            }
        }
    }

    /**
     * Close a result set without throwing an exception.
     *
     * @param rs the result set or null
     */
    public static void closeSilently(ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                // ignore
            }
        }
    }

    /**
     * Open a new database connection with the given settings.
     *
     * @param driver the driver class name
     * @param url the database URL
     * @param user the user name
     * @param password the password
     * @return the database connection
     */
270 271
    public static Connection getConnection(String driver, String url,
            String user, String password) throws SQLException {
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
        Properties prop = new Properties();
        if (user != null) {
            prop.setProperty("user", user);
        }
        if (password != null) {
            prop.setProperty("password", password);
        }
        return getConnection(driver, url, prop);
    }

    /**
     * Open a new database connection with the given settings.
     *
     * @param driver the driver class name
     * @param url the database URL
     * @param prop the properties containing at least the user name and password
     * @return the database connection
     */
290 291
    public static Connection getConnection(String driver, String url,
            Properties prop) throws SQLException {
292
        if (StringUtils.isNullOrEmpty(driver)) {
293
            JdbcUtils.load(url);
294
        } else {
295
            Class<?> d = loadUserClass(driver);
296 297 298 299 300 301 302 303 304 305 306 307 308
            if (java.sql.Driver.class.isAssignableFrom(d)) {
                return DriverManager.getConnection(url, prop);
            } else if (javax.naming.Context.class.isAssignableFrom(d)) {
                // JNDI context
                try {
                    Context context = (Context) d.newInstance();
                    DataSource ds = (DataSource) context.lookup(url);
                    String user = prop.getProperty("user");
                    String password = prop.getProperty("password");
                    if (StringUtils.isNullOrEmpty(user) && StringUtils.isNullOrEmpty(password)) {
                        return ds.getConnection();
                    }
                    return ds.getConnection(user, password);
309 310
                } catch (Exception e) {
                    throw DbException.toSQLException(e);
Thomas Mueller's avatar
Thomas Mueller committed
311 312
                }
            } else {
313
                // don't know, but maybe it loaded a JDBC Driver
314
                return DriverManager.getConnection(url, prop);
Thomas Mueller's avatar
Thomas Mueller committed
315
            }
316 317 318 319
        }
        return DriverManager.getConnection(url, prop);
    }

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
    /**
     * Get the driver class name for the given URL, or null if the URL is
     * unknown.
     *
     * @param url the database URL
     * @return the driver class name
     */
    public static String getDriver(String url) {
        if (url.startsWith("jdbc:")) {
            url = url.substring("jdbc:".length());
            for (int i = 0; i < DRIVERS.length; i += 2) {
                String prefix = DRIVERS[i];
                if (url.startsWith(prefix)) {
                    return DRIVERS[i + 1];
                }
            }
        }
        return null;
    }

    /**
     * Load the driver class for the given URL, if the database URL is known.
     *
     * @param url the database URL
     */
345
    public static void load(String url) {
346 347
        String driver = getDriver(url);
        if (driver != null) {
348 349 350
            loadUserClass(driver);
        }
    }
Thomas Mueller's avatar
Thomas Mueller committed
351

352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
    /**
     * Serialize the object to a byte array, using the serializer specified by
     * the connection info if set, or the default serializer.
     *
     * @param obj the object to serialize
     * @param dataHandler provides the object serializer (may be null)
     * @return the byte array
     */
    public static byte[] serialize(Object obj, DataHandler dataHandler) {
        try {
            JavaObjectSerializer handlerSerializer = null;
            if (dataHandler != null) {
                handlerSerializer = dataHandler.getJavaObjectSerializer();
            }
            if (handlerSerializer != null) {
                return handlerSerializer.serialize(obj);
            }
            if (serializer != null) {
                return serializer.serialize(obj);
            }
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ObjectOutputStream os = new ObjectOutputStream(out);
            os.writeObject(obj);
            return out.toByteArray();
        } catch (Throwable e) {
            throw DbException.get(ErrorCode.SERIALIZATION_FAILED_1, e, e.toString());
        }
    }

    /**
     * De-serialize the byte array to an object, eventually using the serializer
     * specified by the connection info.
     *
     * @param data the byte array
     * @param dataHandler provides the object serializer (may be null)
     * @return the object
     * @throws DbException if serialization fails
     */
    public static Object deserialize(byte[] data, DataHandler dataHandler) {
        try {
            JavaObjectSerializer dbJavaObjectSerializer = null;
            if (dataHandler != null) {
                dbJavaObjectSerializer = dataHandler.getJavaObjectSerializer();
            }
            if (dbJavaObjectSerializer != null) {
                return dbJavaObjectSerializer.deserialize(data);
            }
            if (serializer != null) {
                return serializer.deserialize(data);
            }
            ByteArrayInputStream in = new ByteArrayInputStream(data);
            ObjectInputStream is;
            if (SysProperties.USE_THREAD_CONTEXT_CLASS_LOADER) {
                final ClassLoader loader = Thread.currentThread().getContextClassLoader();
                is = new ObjectInputStream(in) {
                    @Override
                    protected Class<?> resolveClass(ObjectStreamClass desc)
                            throws IOException, ClassNotFoundException {
                        try {
                            return Class.forName(desc.getName(), true, loader);
                        } catch (ClassNotFoundException e) {
                            return super.resolveClass(desc);
                        }
                    }
                };
            } else {
                is = new ObjectInputStream(in);
            }
            return is.readObject();
        } catch (Throwable e) {
            throw DbException.get(ErrorCode.DESERIALIZATION_FAILED_1, e, e.toString());
423 424 425
        }
    }

426
}