public StatisticsQueue getStatisticsQueue() { if (statisticsQueue == null) { throw new InitException("cannot collect statistics if this was not configured in activejdbc.properties file. Add 'collectStatistics = true' to it."); } return statisticsQueue; }
private void checkProps(String driver, String userName, String password, String url, String env){ if (driver == null || userName == null || password == null || url == null){ throw new InitException("Four JDBC properties are expected: driver, username, password, url for environment: " + env); } }
private static <T extends Model> Class<T> modelClass() { throw new InitException("failed to determine Model class name, are you sure models have been instrumented?"); }
private void loadProjectProperties() { try { InputStream in = getClass().getResourceAsStream("/activejdbc.properties"); if (in != null) { properties.load(in); } } catch (IOException e){ throw new InitException(e); } }
/** * Retrieves all attribute names. * * @return all attribute names. */ protected Set<String> getAttributeNames() { if(columnMetadata == null || columnMetadata.isEmpty()) throw new InitException("Failed to find table: " + getTableName()); return Collections.unmodifiableSet(columnMetadata.keySet()); }
/** * Provides column metadata map, keyed by attribute names. * Table columns correspond to ActiveJDBC model attributes. * * @return Provides column metadata map, keyed by attribute names. */ public Map<String, ColumnMetadata> getColumnMetadata() { if(columnMetadata == null || columnMetadata.isEmpty()) throw new InitException("Failed to find table: " + getTableName()); return Collections.unmodifiableMap(columnMetadata); }
public static <T extends Model> T create(Class<T> clazz, Object... namesAndValues) { try { return clazz.newInstance().set(namesAndValues); } catch (IllegalArgumentException e) { throw e; } catch (ClassCastException e) { throw new IllegalArgumentException("All even arguments must be strings"); } catch (DBException e) { throw e; } catch (Exception e) { throw new InitException("Model '" + clazz.getName() + "' must provide a default constructor.", e); } }
/** * Returns model class for a table name, null if not found. * * @param table table name * @param suppressException true to suppress exception * @return model class for a table name, null if not found.s */ protected Class<? extends Model> getModelClass(String table, boolean suppressException) { Class<? extends Model> modelClass = metaModels.getModelClass(table); if(modelClass == null && !suppressException){ throw new InitException("failed to locate meta model for: " + table + ", are you sure this is correct table name?"); }else{ return modelClass; } }
public EHCache3Manager() throws ClassNotFoundException, SAXException, InstantiationException, IOException, IllegalAccessException { URL url = getClass().getResource("/activejdbc-ehcache.xml"); if(url == null){ throw new InitException("You are using " + getClass().getName() + " but failed to provide a EHCache configuration file on classpath: activejdbc-ehcache.xml"); } XmlConfiguration xmlConfiguration = new XmlConfiguration(url); cacheTemplate = xmlConfiguration.newCacheConfigurationBuilderFromTemplate("activejdbc", String.class, Object.class); if(cacheTemplate == null){ throw new InitException("Please, provide a <cache-template name=\"activejdbc\"> element in activejdbc-ehcache.xml file"); } cacheManager = CacheManagerBuilder.newCacheManager(xmlConfiguration); cacheManager.init(); }
protected static Set<Class<? extends Model>> getModelsForDb(String dbName) throws ClassNotFoundException { Set<String> modelClassNames = getModelMap().get(dbName); Set<Class<? extends Model>> classSet = new HashSet<>(); if (modelClassNames != null) { for (String className : modelClassNames) { Class modelClass = Class.forName(className); if (!modelClass.equals(Model.class) && Model.class.isAssignableFrom(modelClass)) { String realDbName = MetaModel.getDbName(modelClass); if (realDbName.equals(dbName)) { classSet.add(modelClass); } else { throw new InitException("invalid database association for the " + className + ". Real database name: " + realDbName); } } else { throw new InitException("invalid class in the models list: " + className); } } } if (classSet.isEmpty()){ throw new InitException("you are trying to work with models, but no models are found. Maybe you have " + "no models in project, or you did not instrument the models. It is expected that you have " + "a file activejdbc_models.properties on classpath"); } return classSet; } //
static <T extends Model> T instance(Map<String, Object> map, MetaModel metaModel, Class<T> clazz) { try { T instance = clazz.newInstance(); instance.hydrate(map, true); return instance; } catch(InstantiationException e) { throw new InitException("Failed to create a new instance of: " + metaModel.getModelClass() + ", are you sure this class has a default constructor?"); } catch(DBException e) { throw e; } catch(InitException e) { throw e; } catch (IllegalAccessException e) { throw new RuntimeException(e.getMessage(), e); } }
private boolean loadStaticMetadata() { try { Enumeration<URL> urls = Registry.instance().getClass().getClassLoader().getResources("activejdbc_metadata.json"); staticMetadataStatus = urls.hasMoreElements() ? STATIC_METADATA_LOADED : STATIC_METADATA_CHECKED; while(urls.hasMoreElements()) { URL url = urls.nextElement(); LogFilter.log(LOGGER, LogLevel.INFO, "Loading metadata from: {}", url.toExternalForm()); metaModels.fromJSON(Util.read(url.openStream())); } return staticMetadataStatus == STATIC_METADATA_LOADED; } catch(IOException e) { throw new InitException(e); } }
/** * Set to true in order to rollback a transaction at the end of the test. * <p> * <em> * WARNING: if you set this value to false inside your test, the framework will not * clean any remaining data you insert into your test database. Basically, this is a * "manual mode" where you are responsible for cleaning after yourself. * </em> * </p> * * @param rollback true to rollback transactions at the end of the test, false to not rollback. */ public void setRollback(boolean rollback) { if(!suppressDb){ this.rollback = rollback; Map<String, Connection> connections = DB.connections(); for(String name: connections.keySet()){ try { boolean autocommit = !rollback; connections.get(name).setAutoCommit(autocommit); } catch (SQLException e) { throw new InitException(e); } } } }
protected Configuration(){ loadProjectProperties(); loadOverridesFromSystemProperties(); loadConnectionsSpecs(); String loggerClass = properties.getProperty(PropertyName.ActiveJdbcLogger.name); if(loggerClass != null){ try { activeLogger = (ActiveJDBCLogger) Class.forName(loggerClass).newInstance(); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { throw new InitException("Failed to initialize a ActiveJDBCLogger. Please, ensure that the property " + "'activejdbc.logger' points to correct class which extends '" + ActiveJDBCLogger.class.getName() + "' and provides a default constructor.", e); } } }
private DB open(String driver, String url, String user, String password, Properties properties){ checkExistingConnection(name); try { Class.forName(driver); Connection connection; connection = properties == null ? DriverManager.getConnection(url, user, password) : DriverManager.getConnection(url, properties); LogFilter.log(LOGGER, LogLevel.DEBUG, "Opened connection: " + connection); ConnectionsAccess.attach(name, connection, url); return this; } catch (Exception e) { throw new InitException("Failed to connect to JDBC URL: " + url + " with user: " + user, e); } }
/** * This method is used internally by framework. * * @param context context. * @param jndiName JNDI name. */ private DB openContext(InitialContext context, String jndiName) { try { DataSource ds = (DataSource) context.lookup(jndiName); Connection connection = ds.getConnection(); LogFilter.log(LOGGER, LogLevel.DEBUG, "Opened connection: " + connection); ConnectionsAccess.attach(name, connection, jndiName); return this; } catch (Exception e) { throw new InitException("Failed to connect to JNDI name: " + jndiName, e); } }
throw new InitException(e);
private static synchronized Map<String, Set<String>> getModelMap() { if (modelMap == null) { try { modelMap = new HashMap<>(); Enumeration<URL> urls = Registry.instance().getClass().getClassLoader().getResources("activejdbc_models.properties"); while(urls.hasMoreElements()) { URL url = urls.nextElement(); LogFilter.log(LOGGER, LogLevel.INFO, "Loading models from: {}", url.toExternalForm()); String modelsFile = Util.read(url.openStream()); String[] lines = Util.split(modelsFile, System.getProperty("line.separator")); for(String line : lines) { String[] parts = Util.split(line, ':'); String modelName = parts[0]; String dbName = parts[1]; Set<String> modelNames = modelMap.computeIfAbsent(dbName, k -> new HashSet<>()); if (!modelNames.add(modelName)) { throw new InitException(String.format("Model '{}' already exists for database '{}'", modelName, dbName)); } } } } catch(IOException e) { throw new InitException(e); } } return modelMap; }
/** * Opens a connection from a datasource. This methods gives a high level control while sourcing a DB connection. * * @param datasource datasource will be used to acquire a connection. */ public DB open(DataSource datasource) { checkExistingConnection(name); try { Connection connection = datasource.getConnection(); LogFilter.log(LOGGER, LogLevel.DEBUG, "Opened connection: " + connection); ConnectionsAccess.attach(name, connection, datasource.toString()); return this; } catch (SQLException e) { throw new InitException(e); } }
/** * Opens a connection from JNDI based on a registered name. This assumes that there is a <code>jndi.properties</code> * file with proper JNDI configuration in it. * * @param jndiName name of a configured data source. */ public DB open(String jndiName) { checkExistingConnection(name); try { Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup(jndiName); Connection connection = ds.getConnection(); LogFilter.log(LOGGER, LogLevel.DEBUG, "Opened connection: " + connection); ConnectionsAccess.attach(name, connection, jndiName); return this; } catch (Exception e) { throw new InitException("Failed to connect to JNDI name: " + jndiName, e); } }