001package co.codewizards.cloudstore.core.util; 002 003import static java.util.Objects.*; 004 005import java.sql.DriverManager; 006import java.sql.SQLException; 007import java.util.regex.Pattern; 008 009import co.codewizards.cloudstore.core.config.Config; 010import co.codewizards.cloudstore.core.config.ConfigImpl; 011import co.codewizards.cloudstore.core.oio.File; 012 013public class DerbyUtil { 014 015 /** 016 * The Derby database was shut down successfully. 017 */ 018 private static final int DERBY_ERROR_CODE_SHUTDOWN_DATABASE_SUCCESSFULLY = 45000; 019 /** 020 * The Derby database which was shut down was not running (the shut down had no effect). 021 */ 022 private static final int DERBY_ERROR_CODE_SHUTDOWN_DATABASE_WAS_NOT_RUNNING = 40000; 023 024 public static final String DERBY_PROPERTIES_PREFIX = "derby."; 025 026 public static final String CONFIG_KEY_DERBY_LANGUAGE_STATEMENT_CACHE_SIZE = "derby.language.statementCacheSize"; 027 028 public static final String DEFAULT_DERBY_LANGUAGE_STATEMENT_CACHE_SIZE = "500"; 029 030 private DerbyUtil() { } 031 032 public static void shutdownDerbyDatabase(String connectionURL) { 033 String shutdownConnectionURL = requireNonNull(connectionURL, "connectionURL") + ";shutdown=true"; 034 try { 035 DriverManager.getConnection(shutdownConnectionURL); 036 } catch (SQLException e) { 037 int errorCode = e.getErrorCode(); 038 if (DERBY_ERROR_CODE_SHUTDOWN_DATABASE_SUCCESSFULLY != errorCode && 039 DERBY_ERROR_CODE_SHUTDOWN_DATABASE_WAS_NOT_RUNNING != errorCode) { 040 throw new RuntimeException(e); 041 } 042 } 043 } 044 045 public static void setLogFile(File file) { 046 // First pass all config-properties whose key starts with "derby." as system-property. 047 setDerbyPropertiesAsSystemProperties(); 048 049 // Then set the actual derby-log-file. 050 System.setProperty("derby.stream.error.file", requireNonNull(file, "file").getAbsolutePath()); 051 } 052 053 protected static void setDerbyPropertiesAsSystemProperties() { 054 Config config = ConfigImpl.getInstance(); 055 Pattern regex = Pattern.compile(Pattern.quote(DERBY_PROPERTIES_PREFIX) + ".*"); 056 for (String key : config.getKey2GroupsMatching(regex).keySet()) { 057 String value = config.getProperty(key, null); 058 System.setProperty(key, value); 059 } 060 061 String derbyLanguageStatementCacheSize = config.getPropertyAsNonEmptyTrimmedString( 062 CONFIG_KEY_DERBY_LANGUAGE_STATEMENT_CACHE_SIZE, 063 DEFAULT_DERBY_LANGUAGE_STATEMENT_CACHE_SIZE); 064 065 System.setProperty(CONFIG_KEY_DERBY_LANGUAGE_STATEMENT_CACHE_SIZE, derbyLanguageStatementCacheSize); 066 } 067}