/**
   * Check the autoCommit and Transaction Isolation levels of the DataSource.
   *
   * <p>If autoCommit is true this could be a real problem.
   *
   * <p>If the Isolation level is not READ_COMMITED then optimistic concurrency checking may not
   * work as expected.
   */
  private boolean checkDataSource(ServerConfig serverConfig) {

    if (serverConfig.getDataSource() == null) {
      if (serverConfig.getDataSourceConfig().isOffline()) {
        // this is ok - offline DDL generation etc
        return false;
      }
      throw new RuntimeException("DataSource not set?");
    }

    Connection c = null;
    try {
      c = serverConfig.getDataSource().getConnection();

      if (c.getAutoCommit()) {
        String m = "DataSource [" + serverConfig.getName() + "] has autoCommit defaulting to true!";
        logger.warning(m);
      }

      return true;

    } catch (SQLException ex) {
      throw new PersistenceException(ex);

    } finally {
      if (c != null) {
        try {
          c.close();
        } catch (SQLException ex) {
          logger.log(Level.SEVERE, null, ex);
        }
      }
    }
  }
  /** Create and return the CacheManager. */
  private ServerCacheManager getCacheManager(ServerConfig serverConfig) {

    ServerCacheManager serverCacheManager = serverConfig.getServerCacheManager();
    if (serverCacheManager != null) {
      return serverCacheManager;
    }

    // reasonable default settings are for a cache per bean type
    ServerCacheOptions beanOptions = new ServerCacheOptions();
    beanOptions.setMaxSize(GlobalProperties.getInt("cache.maxSize", 1000));
    // maxIdleTime 10 minutes
    beanOptions.setMaxIdleSecs(GlobalProperties.getInt("cache.maxIdleTime", 60 * 10));
    // maxTimeToLive 6 hrs
    beanOptions.setMaxSecsToLive(GlobalProperties.getInt("cache.maxTimeToLive", 60 * 60 * 6));

    // reasonable default settings for the query cache per bean type
    ServerCacheOptions queryOptions = new ServerCacheOptions();
    queryOptions.setMaxSize(GlobalProperties.getInt("querycache.maxSize", 100));
    // maxIdleTime 10 minutes
    queryOptions.setMaxIdleSecs(GlobalProperties.getInt("querycache.maxIdleTime", 60 * 10));
    // maxTimeToLive 6 hours
    queryOptions.setMaxSecsToLive(GlobalProperties.getInt("querycache.maxTimeToLive", 60 * 60 * 6));

    ServerCacheFactory cacheFactory = serverConfig.getServerCacheFactory();
    if (cacheFactory == null) {
      cacheFactory = new DefaultServerCacheFactory();
    }

    return new DefaultServerCacheManager(cacheFactory, beanOptions, queryOptions);
  }
 /** Construct with a naming convention and platform specific DDL. */
 public BaseTableDdl(ServerConfig serverConfig, PlatformDdl platformDdl) {
   this.namingConvention = serverConfig.getNamingConvention();
   this.naming = serverConfig.getConstraintNaming();
   this.historyTableSuffix = serverConfig.getHistoryTableSuffix();
   this.platformDdl = platformDdl;
   this.platformDdl.configure(serverConfig);
 }
Esempio n. 4
0
  public Database(Zones plugin) {
    /*
     * Hacky but does the job.
     * Reason for doing this:
     * i don't want to be the 5th plugins that has just a config file for
     * database connection information....
     *
     * So i just grab it from bukkit :).
     */
    ServerConfig db = new ServerConfig();
    plugin.getServer().configureDbConfig(db);

    try {
      Class.forName(db.getDataSourceConfig().getDriver());
    } catch (Exception e) {
      Zones.log.warning("[Zones]Warning JDBC not available.");
    }

    this.url = db.getDataSourceConfig().getUrl();
    this.username = db.getDataSourceConfig().getUsername();
    this.password = db.getDataSourceConfig().getPassword();

    this.plugin = plugin;
    checkVersion();
  }
  public InternalConfiguration(
      XmlConfig xmlConfig,
      ClusterManager clusterManager,
      ServerCacheManager cacheManager,
      SpiBackgroundExecutor backgroundExecutor,
      ServerConfig serverConfig,
      BootupClasses bootupClasses,
      PstmtBatch pstmtBatch) {

    this.xmlConfig = xmlConfig;
    this.pstmtBatch = pstmtBatch;
    this.clusterManager = clusterManager;
    this.backgroundExecutor = backgroundExecutor;
    this.cacheManager = cacheManager;
    this.serverConfig = serverConfig;
    this.bootupClasses = bootupClasses;
    this.expressionFactory = new DefaultExpressionFactory();

    this.typeManager = new DefaultTypeManager(serverConfig, bootupClasses);
    this.binder = new Binder(typeManager);

    this.resourceManager = ResourceManagerFactory.createResourceManager(serverConfig);
    this.deployOrmXml = new DeployOrmXml(resourceManager.getResourceSource());
    this.deployInherit = new DeployInherit(bootupClasses);

    this.deployCreateProperties = new DeployCreateProperties(typeManager);
    this.deployUtil = new DeployUtil(typeManager, serverConfig);

    this.beanDescriptorManager = new BeanDescriptorManager(this);
    beanDescriptorManager.deploy();

    this.debugLazyLoad = new DebugLazyLoad(serverConfig.isDebugLazyLoad());

    this.transactionManager =
        new TransactionManager(
            clusterManager,
            backgroundExecutor,
            serverConfig,
            beanDescriptorManager,
            this.getBootupClasses());

    this.cQueryEngine =
        new CQueryEngine(serverConfig.getDatabasePlatform(), binder, backgroundExecutor);

    ExternalTransactionManager externalTransactionManager =
        serverConfig.getExternalTransactionManager();
    if (externalTransactionManager == null && serverConfig.isUseJtaTransactionManager()) {
      externalTransactionManager = new JtaTransactionManager();
    }
    if (externalTransactionManager != null) {
      externalTransactionManager.setTransactionManager(transactionManager);
      this.transactionScopeManager =
          new ExternalTransactionScopeManager(transactionManager, externalTransactionManager);
      logger.info("Using Transaction Manager [" + externalTransactionManager.getClass() + "]");
    } else {
      this.transactionScopeManager = new DefaultTransactionScopeManager(transactionManager);
    }
  }
  private EbeanServer initializeDatabase(boolean dropAndCreateDatabase, String dbName) {
    ServerConfig config = new ServerConfig();
    config.setName(dbName);
    DataSourceConfig hdDB = new DataSourceConfig();
    hdDB.setDriver("org.h2.Driver");
    hdDB.setUsername("test");
    hdDB.setPassword("test");
    hdDB.setUrl("jdbc:h2:mem:tests;DB_CLOSE_DELAY=-1");
    hdDB.setHeartbeatSql("select 1 ");
    config.setDataSourceConfig(hdDB);

    config.setDefaultServer(false);
    config.setRegister(false);

    if (dropAndCreateDatabase) {
      config.setDdlGenerate(true);
      config.setDdlRun(true);
      // config.setDebugSql(true);
    }

    config.addClass(Viite.class);
    config.addClass(Attribuutti.class);

    return EbeanServerFactory.create(config);
  }
  /** Set the DatabasePlatform if it has not already been set. */
  private void setDatabasePlatform(ServerConfig config) {

    DatabasePlatform dbPlatform = config.getDatabasePlatform();
    if (dbPlatform == null) {

      DatabasePlatformFactory factory = new DatabasePlatformFactory();

      DatabasePlatform db = factory.create(config);
      config.setDatabasePlatform(db);
      logger.info("DatabasePlatform name:" + config.getName() + " platform:" + db.getName());
    }
  }
  public JsonContext createJsonContext(SpiEbeanServer server) {

    String s = serverConfig.getProperty("json.pretty", "false");
    boolean dfltPretty = "true".equalsIgnoreCase(s);

    s = serverConfig.getProperty("json.jsonValueAdapter", null);

    JsonValueAdapter va = new DefaultJsonValueAdapter();
    if (s != null) {
      va = (JsonValueAdapter) ClassUtil.newInstance(s, this.getClass());
    }
    return new DJsonContext(server, va, dfltPretty);
  }
  /**
   * Get the entities, scalarTypes, Listeners etc combining the class registered ones with the
   * already created instances.
   */
  private BootupClasses getBootupClasses(ServerConfig serverConfig) {

    BootupClasses bootupClasses = getBootupClasses1(serverConfig);
    bootupClasses.addPersistControllers(serverConfig.getPersistControllers());
    bootupClasses.addTransactionEventListeners(serverConfig.getTransactionEventListeners());
    bootupClasses.addPersistListeners(serverConfig.getPersistListeners());
    bootupClasses.addQueryAdapters(serverConfig.getQueryAdapters());
    bootupClasses.addServerConfigStartup(serverConfig.getServerConfigStartupListeners());

    // run any ServerConfigStartup instances
    bootupClasses.runServerConfigStartup(serverConfig);
    return bootupClasses;
  }
  private SpiBackgroundExecutor createBackgroundExecutor(
      ServerConfig serverConfig, int uniqueServerId) {

    String namePrefix = "Ebean-" + serverConfig.getName();

    // the size of the pool for executing periodic tasks (such as cache
    // flushing)
    int schedulePoolSize = GlobalProperties.getInt("backgroundExecutor.schedulePoolsize", 1);

    // the side of the main pool for immediate background task execution
    int minPoolSize = GlobalProperties.getInt("backgroundExecutor.minPoolSize", 1);
    int poolSize = GlobalProperties.getInt("backgroundExecutor.poolsize", 20);
    int maxPoolSize = GlobalProperties.getInt("backgroundExecutor.maxPoolSize", poolSize);

    int idleSecs = GlobalProperties.getInt("backgroundExecutor.idlesecs", 60);
    int shutdownSecs = GlobalProperties.getInt("backgroundExecutor.shutdownSecs", 30);

    boolean useTrad = GlobalProperties.getBoolean("backgroundExecutor.traditional", true);

    if (useTrad) {
      // this pool will use Idle seconds between min and max so I think it is
      // better
      // as it will let the thread count float between the min and max
      ThreadPool pool = ThreadPoolManager.getThreadPool(namePrefix);
      pool.setMinSize(minPoolSize);
      pool.setMaxSize(maxPoolSize);
      pool.setMaxIdleTime(idleSecs * 1000);
      return new TraditionalBackgroundExecutor(pool, schedulePoolSize, shutdownSecs, namePrefix);
    } else {
      return new DefaultBackgroundExecutor(
          poolSize, schedulePoolSize, idleSecs, shutdownSecs, namePrefix);
    }
  }
Esempio n. 11
0
  private void tryLoadOldSensors() {

    java.io.File f = null;

    for (File fi : this.getDataFolder().listFiles()) {
      if (fi.getName().toLowerCase().contains("minecartmaniarebornsigncommands.db")) {
        f = fi;
        break;
      }
    }

    if (f == null) {
      return;
    }

    Logger.debug("Found old sensor DB. Attempting load...");

    com.avaje.ebean.config.DataSourceConfig dsc = new com.avaje.ebean.config.DataSourceConfig();
    dsc.setUsername("temp");
    dsc.setPassword("temp");
    dsc.setDriver("org.sqlite.JDBC");
    dsc.setIsolationLevel(8);

    dsc.setUrl("jdbc:sqlite:plugins/minecartmania/minecartmaniarebornsigncommands.db");

    ServerConfig config = new ServerConfig();
    config.setDataSourceConfig(dsc);
    config.setName("Old DB");
    config.addClass(com.afforess.minecartmaniasigncommands.sensor.SensorDataTable.class);
    config.addJar("MinecartMania.jar");
    SensorManager.database = com.avaje.ebean.EbeanServerFactory.create(config);

    SensorManager.loadsensors();

    if (SensorManager.getCount() > 0) {
      Logger.severe("Found sensors in old db, moving...");
      // loaded old sensors
      for (Sensor s : SensorManager.getSensorList().values()) {
        SensorManager.saveSensor(s);
      }
      Logger.severe("Complete. Removing old db.");
    }

    SensorManager.database = this.getDatabase();

    f.delete();
  }
Esempio n. 12
0
  /**
   * Populates a given {@link com.avaje.ebean.config.ServerConfig} with values attributes to this
   * server
   *
   * @param dbConfig ServerConfig to populate
   */
  public void configureDbConfig(com.avaje.ebean.config.ServerConfig dbConfig) {
    com.avaje.ebean.config.DataSourceConfig ds = new com.avaje.ebean.config.DataSourceConfig();
    ds.setDriver(config.getString("database.driver", "org.sqlite.JDBC"));
    ds.setUrl(config.getString("database.url", "jdbc:sqlite:{DIR}{NAME}.db"));
    ds.setUsername(config.getString("database.username", "glow"));
    ds.setPassword(config.getString("database.password", "stone"));
    ds.setIsolationLevel(
        com.avaje.ebeaninternal.server.lib.sql.TransactionIsolation.getLevel(
            config.getString("database.isolation", "SERIALIZABLE")));

    if (ds.getDriver().contains("sqlite")) {
      dbConfig.setDatabasePlatform(new com.avaje.ebean.config.dbplatform.SQLitePlatform());
      dbConfig.getDatabasePlatform().getDbDdlSyntax().setIdentity("");
    }

    dbConfig.setDataSourceConfig(ds);
  }
  /** Set the naming convention to underscore if it has not already been set. */
  private void setNamingConvention(ServerConfig config) {
    if (config.getNamingConvention() == null) {
      UnderscoreNamingConvention nc = new UnderscoreNamingConvention();
      config.setNamingConvention(nc);

      String v = config.getProperty("namingConvention.useForeignKeyPrefix");
      if (v != null) {
        boolean useForeignKeyPrefix = Boolean.valueOf(v);
        nc.setUseForeignKeyPrefix(useForeignKeyPrefix);
      }

      String sequenceFormat = config.getProperty("namingConvention.sequenceFormat");
      if (sequenceFormat != null) {
        nc.setSequenceFormat(sequenceFormat);
      }
    }
  }
  /** Create using the ServerConfig object to configure the server. */
  public static EbeanServer create(ServerConfig config) {

    if (config.getName() == null) {
      throw new PersistenceException("The name is null (it is required)");
    }

    EbeanServer server = serverFactory.createServer(config);

    if (config.isDefaultServer()) {
      GlobalProperties.setSkipPrimaryServer(true);
    }
    if (config.isRegister()) {
      Ebean.register(server, config.isDefaultServer());
    }

    return server;
  }
Esempio n. 15
0
  @Override
  public void configureDbConfig(com.avaje.ebean.config.ServerConfig dbConfig) {
    com.avaje.ebean.config.DataSourceConfig ds = new com.avaje.ebean.config.DataSourceConfig();
    ds.setDriver(config.getString(ServerConfig.Key.DB_DRIVER));
    ds.setUrl(config.getString(ServerConfig.Key.DB_URL));
    ds.setUsername(config.getString(ServerConfig.Key.DB_USERNAME));
    ds.setPassword(config.getString(ServerConfig.Key.DB_PASSWORD));
    ds.setIsolationLevel(
        com.avaje.ebeaninternal.server.lib.sql.TransactionIsolation.getLevel(
            config.getString(ServerConfig.Key.DB_ISOLATION)));

    if (ds.getDriver().contains("sqlite")) {
      dbConfig.setDatabasePlatform(new com.avaje.ebean.config.dbplatform.SQLitePlatform());
      dbConfig.getDatabasePlatform().getDbDdlSyntax().setIdentity("");
    }

    dbConfig.setDataSourceConfig(ds);
  }
Esempio n. 16
0
  @Override
  public void configureDbConfig(ServerConfig config) {
    DataSourceConfig ds = new DataSourceConfig();
    ds.setDriver(configuration.getString("database.driver"));
    ds.setUrl(configuration.getString("database.url"));
    ds.setUsername(configuration.getString("database.username"));
    ds.setPassword(configuration.getString("database.password"));
    ds.setIsolationLevel(
        TransactionIsolation.getLevel(configuration.getString("database.isolation")));

    if (ds.getDriver().contains("sqlite")) {
      config.setDatabasePlatform(new SQLitePlatform());
      config.getDatabasePlatform().getDbDdlSyntax().setIdentity("");
    } else if (ds.getDriver().contains("mysql")) {
      theLogger.warning("MySQL is presently unsupported for CraftForge");
    }

    config.setDataSourceConfig(ds);
  }
  /** Get the class based entities, scalarTypes, Listeners etc. */
  private BootupClasses getBootupClasses1(ServerConfig serverConfig) {

    List<Class<?>> entityClasses = serverConfig.getClasses();
    if (entityClasses != null && entityClasses.size() > 0) {
      // use classes we explicitly added via configuration
      return new BootupClasses(serverConfig.getClasses());
    }

    List<String> jars = serverConfig.getJars();
    List<String> packages = serverConfig.getPackages();

    if ((packages != null && !packages.isEmpty()) || (jars != null && !jars.isEmpty())) {
      // filter by package name
      BootupClassPathSearch search = new BootupClassPathSearch(null, packages, jars);
      return search.getBootupClasses();
    }

    // just use classes we can find via class path search
    return bootupClassSearch.getBootupClasses().createCopy();
  }
Esempio n. 18
0
  private void prepareDatabase(
      String driver, String url, String username, String password, String isolation) {
    // Setup the data source
    DataSourceConfig ds = new DataSourceConfig();
    ds.setDriver(driver);
    ds.setUrl(replaceDatabaseString(url));
    ds.setUsername(username);
    ds.setPassword(password);
    ds.setIsolationLevel(TransactionIsolation.getLevel(isolation));

    // Setup the server configuration
    ServerConfig sc = new ServerConfig();
    sc.setDefaultServer(false);
    sc.setRegister(false);
    sc.setName(ds.getUrl().replaceAll("[^a-zA-Z0-9]", ""));

    // Get all persistent classes
    List<Class<?>> classes = getDatabaseClasses();

    // Do a sanity check first
    if (classes.size() == 0) {
      // Exception: There is no use in continuing to load this database
      throw new RuntimeException("Database has been enabled, but no classes are registered to it");
    }

    // Register them with the EbeanServer
    sc.setClasses(classes);

    // Check if the SQLite JDBC supplied with Bukkit is being used
    if (ds.getDriver().equalsIgnoreCase("org.sqlite.JDBC")) {
      // Remember the database is a SQLite-database
      usingSQLite = true;

      // Modify the platform, as SQLite has no AUTO_INCREMENT field
      sc.setDatabasePlatform(new SQLitePlatform());
      sc.getDatabasePlatform().getDbDdlSyntax().setIdentity("");
    }

    prepareDatabaseAdditionalConfig(ds, sc);

    // Finally the data source
    sc.setDataSourceConfig(ds);

    // Store the ServerConfig
    serverConfig = sc;
  }
  public DefaultAutoTuneService(SpiEbeanServer server, ServerConfig serverConfig) {

    AutoTuneConfig config = serverConfig.getAutoTuneConfig();

    this.server = server;
    this.queryTuning = config.isQueryTuning();
    this.profiling = config.isProfiling();
    this.tuningFile = config.getQueryTuningFile();
    this.profilingFile = config.getProfilingFile();
    this.profilingUpdateFrequency = config.getProfilingUpdateFrequency();
    this.serverName = server.getName();
    this.profileManager = new ProfileManager(config, server);
    this.queryTuner = new BaseQueryTuner(config, server, profileManager);
    this.skipGarbageCollectionOnShutdown = config.isSkipGarbageCollectionOnShutdown();
    this.skipProfileReportingOnShutdown = config.isSkipProfileReportingOnShutdown();
    this.defaultGarbageCollectionWait = (long) config.getGarbageCollectionWait();
  }
  private DataSource getDataSourceFromConfig(ServerConfig config) {

    DataSource ds = null;

    if (config.getDataSourceJndiName() != null) {
      ds = jndiDataSourceFactory.lookup(config.getDataSourceJndiName());
      if (ds == null) {
        String m =
            "JNDI lookup for DataSource " + config.getDataSourceJndiName() + " returned null.";
        throw new PersistenceException(m);
      } else {
        return ds;
      }
    }

    DataSourceConfig dsConfig = config.getDataSourceConfig();
    if (dsConfig == null) {
      String m = "No DataSourceConfig definded for " + config.getName();
      throw new PersistenceException(m);
    }

    if (dsConfig.isOffline()) {
      if (config.getDatabasePlatformName() == null) {
        String m = "You MUST specify a DatabasePlatformName on ServerConfig when offline";
        throw new PersistenceException(m);
      }
      return null;
    }

    if (dsConfig.getHeartbeatSql() == null) {
      // use default heartbeatSql from the DatabasePlatform
      String heartbeatSql = getHeartbeatSql(dsConfig.getDriver());
      dsConfig.setHeartbeatSql(heartbeatSql);
    }

    return DataSourceGlobalManager.getDataSource(config.getName(), dsConfig);
  }
Esempio n. 21
0
  /**
   * Initializes this plugin with the given variables.
   *
   * <p>This method should never be called manually.
   *
   * @param loader PluginLoader that is responsible for this plugin
   * @param server Server instance that is running this plugin
   * @param description PluginDescriptionFile containing metadata on this plugin
   * @param dataFolder Folder containing the plugin's data
   * @param file File containing this plugin
   * @param classLoader ClassLoader which holds this plugin
   */
  protected final void initialize(
      PluginLoader loader,
      Server server,
      PluginDescriptionFile description,
      File dataFolder,
      File file,
      ClassLoader classLoader) {
    if (!initialized) {
      this.initialized = true;
      this.loader = loader;
      this.server = server;
      this.file = file;
      this.description = description;
      this.dataFolder = dataFolder;
      this.classLoader = classLoader;
      this.configFile = new File(dataFolder, "config.yml");

      if (description.isDatabaseEnabled()) {
        ServerConfig db = new ServerConfig();

        db.setDefaultServer(false);
        db.setRegister(false);
        db.setClasses(getDatabaseClasses());
        db.setName(description.getName());
        server.configureDbConfig(db);

        DataSourceConfig ds = db.getDataSourceConfig();

        ds.setUrl(replaceDatabaseString(ds.getUrl()));
        getDataFolder().mkdirs();

        ClassLoader previous = Thread.currentThread().getContextClassLoader();

        Thread.currentThread().setContextClassLoader(classLoader);
        ebean = EbeanServerFactory.create(db);
        Thread.currentThread().setContextClassLoader(previous);
      }
    }
  }
 /** Set the DataSource if it has not already been set. */
 private void setDataSource(ServerConfig config) {
   if (config.getDataSource() == null) {
     DataSource ds = getDataSourceFromConfig(config);
     config.setDataSource(ds);
   }
 }
 public RelationalQueryEngine createRelationalQueryEngine() {
   return new DefaultRelationalQueryEngine(binder, serverConfig.getDatabaseBooleanTrue());
 }
  /** Create the implementation from the configuration. */
  public SpiEbeanServer createServer(ServerConfig serverConfig) {

    synchronized (this) {
      setNamingConvention(serverConfig);

      BootupClasses bootupClasses = getBootupClasses(serverConfig);

      setDataSource(serverConfig);
      // check the autoCommit and Transaction Isolation
      boolean online = checkDataSource(serverConfig);

      // determine database platform (Oracle etc)
      setDatabasePlatform(serverConfig);
      if (serverConfig.getDbEncrypt() != null) {
        // use a configured DbEncrypt rather than the platform default
        serverConfig.getDatabasePlatform().setDbEncrypt(serverConfig.getDbEncrypt());
      }

      DatabasePlatform dbPlatform = serverConfig.getDatabasePlatform();

      PstmtBatch pstmtBatch = null;

      if (dbPlatform.getName().startsWith("oracle")) {
        PstmtDelegate pstmtDelegate = serverConfig.getPstmtDelegate();
        if (pstmtDelegate == null) {
          // try to provide the
          pstmtDelegate = getOraclePstmtDelegate(serverConfig.getDataSource());
        }
        if (pstmtDelegate != null) {
          // We can support JDBC batching with Oracle
          // via OraclePreparedStatement
          pstmtBatch = new OraclePstmtBatch(pstmtDelegate);
        }
        if (pstmtBatch == null) {
          // We can not support JDBC batching with Oracle
          logger.warning("Can not support JDBC batching with Oracle without a PstmtDelegate");
          serverConfig.setPersistBatching(false);
        }
      }

      // inform the NamingConvention of the associated DatabasePlaform
      serverConfig.getNamingConvention().setDatabasePlatform(serverConfig.getDatabasePlatform());

      ServerCacheManager cacheManager = getCacheManager(serverConfig);

      int uniqueServerId = serverId.incrementAndGet();
      SpiBackgroundExecutor bgExecutor = createBackgroundExecutor(serverConfig, uniqueServerId);

      InternalConfiguration c =
          new InternalConfiguration(
              xmlConfig,
              clusterManager,
              cacheManager,
              bgExecutor,
              serverConfig,
              bootupClasses,
              pstmtBatch);

      DefaultServer server = new DefaultServer(c, cacheManager);

      cacheManager.init(server);

      MBeanServer mbeanServer;
      ArrayList<?> list = MBeanServerFactory.findMBeanServer(null);
      if (list.size() == 0) {
        // probably not running in a server
        mbeanServer = MBeanServerFactory.createMBeanServer();
      } else {
        // use the first MBeanServer
        mbeanServer = (MBeanServer) list.get(0);
      }

      server.registerMBeans(mbeanServer, uniqueServerId);

      // generate and run DDL if required
      executeDDL(server, online);

      // initialise prior to registering with clusterManager
      server.initialise();

      if (online) {
        if (clusterManager.isClustering()) {
          // register the server once it has been created
          clusterManager.registerServer(server);
        }

        // warm the cache in 30 seconds
        int delaySecs = GlobalProperties.getInt("ebean.cacheWarmingDelay", 30);
        long sleepMillis = 1000 * delaySecs;

        if (sleepMillis > 0) {
          Timer t = new Timer("EbeanCacheWarmer", true);
          t.schedule(new CacheWarmer(server), sleepMillis);
        }
      }

      // start any services after registering with clusterManager
      server.start();
      return server;
    }
  }
 public DatabasePlatform getDatabasePlatform() {
   return serverConfig.getDatabasePlatform();
 }
Esempio n. 26
0
  EbeanServer setConfig() {
    // programmatically build a EbeanServer instance
    // specify the configuration...

    ServerConfig config = new ServerConfig();
    config.setName("mysql");

    // Define DataSource parameters
    DataSourceConfig postgresDb = new DataSourceConfig();
    postgresDb.setDriver("com.mysql.jdbc.Driver");
    postgresDb.setUsername("root");
    postgresDb.setPassword("");
    postgresDb.setUrl("jdbc:mysql://127.0.0.1:3306/perbekalan_farmasi");

    // specify a JNDI DataSource
    // config.setDataSourceJndiName("someJndiDataSourceName");

    // set DDL options...
    //    	config.setDdlGenerate(true);
    //    	config.setDdlRun(true);
    config.setDdlGenerate(false);
    config.setDdlRun(false);
    config.setDefaultServer(false);
    config.setRegister(false);

    // automatically determine the DatabasePlatform
    // using the jdbc driver
    config.setDatabasePlatform(new MySqlPlatform());
    config.setDataSourceConfig(postgresDb);
    // specify the entity classes (and listeners etc)
    // ... if these are not specified Ebean will search
    // ... the classpath looking for entity classes.
    //    	config.addClass(Order.class);
    config.addClass(DeletedGoods.class);
    config.addClass(Goods.class);
    config.addClass(GoodsConsumption.class);
    config.addClass(GoodsReception.class);
    config.addClass(Insurance.class);
    config.addClass(Invoice.class);
    config.addClass(InvoiceItem.class);
    config.addClass(PurchaseOrder.class);
    config.addClass(PurchaseOrderItem.class);
    config.addClass(ReqPlanning.class);
    config.addClass(Role.class);
    config.addClass(Setting.class);
    config.addClass(Supplier.class);
    config.addClass(SupplierGoods.class);
    config.addClass(User.class);
    config.addClass(Manufacturer.class);

    //    	...

    // specify jars to search for entity beans
    //    	config.addJar("someJarThatContainsEntityBeans.jar");

    // create the EbeanServer instance
    EbeanServer server = EbeanServerFactory.create(config);

    return server;
  }