Пример #1
0
 protected String getStatus() {
   StringWriter sw = new StringWriter();
   PrintWriter out = new PrintWriter(sw);
   if (datasource == null || !(datasource instanceof ComboPooledDataSource)) {
     out.println("Datasource" + getConfigInfoString() + ":");
     out.println("~~~~~~~~~~~");
     out.println("(not yet connected)");
     return sw.toString();
   }
   ComboPooledDataSource ds = (ComboPooledDataSource) datasource;
   out.println("Datasource" + getConfigInfoString() + ":");
   out.println("~~~~~~~~~~~");
   out.println("Jdbc url: " + ds.getJdbcUrl());
   out.println("Jdbc driver: " + ds.getDriverClass());
   out.println("Jdbc user: "******"Jdbc password: "******"Min pool size: " + ds.getMinPoolSize());
   out.println("Max pool size: " + ds.getMaxPoolSize());
   out.println("Initial pool size: " + ds.getInitialPoolSize());
   out.println("Checkout timeout: " + ds.getCheckoutTimeout());
   return sw.toString();
 }
Пример #2
0
  private static boolean changed() {
    Properties p = Play.configuration;

    if ("mem".equals(p.getProperty("db")) && p.getProperty("db.url") == null) {
      p.put("db.driver", "org.h2.Driver");
      p.put("db.url", "jdbc:h2:mem:play;MODE=MYSQL");
      p.put("db.user", "sa");
      p.put("db.pass", "");
    }

    if ("fs".equals(p.getProperty("db")) && p.getProperty("db.url") == null) {
      p.put("db.driver", "org.h2.Driver");
      p.put(
          "db.url",
          "jdbc:h2:"
              + (new File(Play.applicationPath, "db/h2/play").getAbsolutePath())
              + ";MODE=MYSQL");
      p.put("db.user", "sa");
      p.put("db.pass", "");
    }

    if (p.getProperty("db", "").startsWith("java:") && p.getProperty("db.url") == null) {
      if (DB.datasource == null) {
        return true;
      }
    } else {
      // Internal pool is c3p0, we should call the close() method to destroy it.
      check(p, "internal pool", "db.destroyMethod");

      p.put("db.destroyMethod", "close");
    }

    Matcher m =
        new jregex.Pattern(
                "^mysql:(//)?(({user}[a-zA-Z0-9_]+)(:({pwd}[^@]+))?@)?(({host}[^/]+)/)?({name}[^\\s]+)$")
            .matcher(p.getProperty("db", ""));
    if (m.matches()) {
      String user = m.group("user");
      String password = m.group("pwd");
      String name = m.group("name");
      String host = m.group("host");
      p.put("db.driver", "com.mysql.jdbc.Driver");
      p.put(
          "db.url",
          "jdbc:mysql://"
              + (host == null ? "localhost" : host)
              + "/"
              + name
              + "?useUnicode=yes&characterEncoding=UTF-8&connectionCollation=utf8_general_ci");
      if (user != null) {
        p.put("db.user", user);
      }
      if (password != null) {
        p.put("db.pass", password);
      }
    }

    m =
        new jregex.Pattern(
                "^postgres:(//)?(({user}[a-zA-Z0-9_]+)(:({pwd}[^@]+))?@)?(({host}[^/]+)/)?({name}[^\\s]+)$")
            .matcher(p.getProperty("db", ""));
    if (m.matches()) {
      String user = m.group("user");
      String password = m.group("pwd");
      String name = m.group("name");
      String host = m.group("host");
      p.put("db.driver", "org.postgresql.Driver");
      p.put("db.url", "jdbc:postgresql://" + (host == null ? "localhost" : host) + "/" + name);
      if (user != null) {
        p.put("db.user", user);
      }
      if (password != null) {
        p.put("db.pass", password);
      }
    }

    if (p.getProperty("db.url") != null && p.getProperty("db.url").startsWith("jdbc:h2:mem:")) {
      p.put("db.driver", "org.h2.Driver");
      p.put("db.user", "sa");
      p.put("db.pass", "");
    }

    if ((p.getProperty("db.driver") == null) || (p.getProperty("db.url") == null)) {
      return false;
    }

    if (DB.datasource == null) {
      return true;
    } else {
      ComboPooledDataSource ds = (ComboPooledDataSource) DB.datasource;
      if (!p.getProperty("db.driver").equals(ds.getDriverClass())) {
        return true;
      }
      if (!p.getProperty("db.url").equals(ds.getJdbcUrl())) {
        return true;
      }
      if (!p.getProperty("db.user", "").equals(ds.getUser())) {
        return true;
      }
      if (!p.getProperty("db.pass", "").equals(ds.getPassword())) {
        return true;
      }
    }

    if (!p.getProperty("db.destroyMethod", "").equals(DB.destroyMethod)) {
      return true;
    }

    return false;
  }
Пример #3
0
 public String getJdbcUrl() {
   return combods.getJdbcUrl();
 }
Пример #4
0
  /**
   * Detects changes and reconfigures this dbConfig. Returns true if the database was configured
   * (Config info present. An exception is throwns if the config process fails.
   */
  protected boolean configure() {

    // prefix used before all properties when loafing config. default is 'db'
    String propsPrefix;
    if (defaultDbConfigName.equals(dbConfigName)) {
      propsPrefix = "db";
    } else {
      propsPrefix = "db_" + dbConfigName;
    }

    boolean dbConfigured = false;

    if (changed(propsPrefix)) {
      try {

        // We now know that we will either config the db, or fail with exception
        dbConfigured = true;

        Properties p = Play.configuration;

        if (datasource != null) {
          destroy();
        }

        if (p.getProperty(propsPrefix, "").startsWith("java:")) {

          Context ctx = new InitialContext();
          datasource = (DataSource) ctx.lookup(p.getProperty(propsPrefix));

        } else {

          // Try the driver
          String driver = p.getProperty(propsPrefix + ".driver");
          try {
            Driver d = (Driver) Class.forName(driver, true, Play.classloader).newInstance();
            DriverManager.registerDriver(new ProxyDriver(d));
          } catch (Exception e) {
            throw new Exception("Driver not found (" + driver + ")");
          }

          // Try the connection
          Connection fake = null;
          try {
            if (p.getProperty(propsPrefix + ".user") == null) {
              fake = DriverManager.getConnection(p.getProperty(propsPrefix + ".url"));
            } else {
              fake =
                  DriverManager.getConnection(
                      p.getProperty(propsPrefix + ".url"),
                      p.getProperty(propsPrefix + ".user"),
                      p.getProperty(propsPrefix + ".pass"));
            }
          } finally {
            if (fake != null) {
              fake.close();
            }
          }

          ComboPooledDataSource ds = new ComboPooledDataSource();
          ds.setDriverClass(p.getProperty(propsPrefix + ".driver"));
          ds.setJdbcUrl(p.getProperty(propsPrefix + ".url"));
          ds.setUser(p.getProperty(propsPrefix + ".user"));
          ds.setPassword(p.getProperty(propsPrefix + ".pass"));
          ds.setAcquireRetryAttempts(10);
          ds.setCheckoutTimeout(
              Integer.parseInt(p.getProperty(propsPrefix + ".pool.timeout", "5000")));
          ds.setBreakAfterAcquireFailure(false);
          ds.setMaxPoolSize(Integer.parseInt(p.getProperty(propsPrefix + ".pool.maxSize", "30")));
          ds.setMinPoolSize(Integer.parseInt(p.getProperty(propsPrefix + ".pool.minSize", "1")));
          ds.setMaxIdleTimeExcessConnections(
              Integer.parseInt(
                  p.getProperty(propsPrefix + ".pool.maxIdleTimeExcessConnections", "0")));
          ds.setIdleConnectionTestPeriod(10);
          ds.setTestConnectionOnCheckin(true);
          datasource = ds;
          url = ds.getJdbcUrl();
          Connection c = null;
          try {
            c = ds.getConnection();
          } finally {
            if (c != null) {
              c.close();
            }
          }
          Logger.info("Connected to %s", ds.getJdbcUrl());
        }

        destroyMethod = p.getProperty(propsPrefix + ".destroyMethod", "");

      } catch (Exception e) {
        datasource = null;
        Logger.error(
            e,
            "Cannot connected to the database" + getConfigInfoString() + " : %s",
            e.getMessage());
        if (e.getCause() instanceof InterruptedException) {
          throw new DatabaseException(
              "Cannot connected to the database"
                  + getConfigInfoString()
                  + ". Check the configuration.",
              e);
        }
        throw new DatabaseException(
            "Cannot connected to the database" + getConfigInfoString() + ", " + e.getMessage(), e);
      }
    }

    return dbConfigured;
  }
Пример #5
0
  @SuppressWarnings("unchecked")
  @Override
  public void onApplicationStart() {
    //
    //	NOTE: this uses the JPA class to store the request's entityManagerFactory.
    //	The trick is that the MJPAPlugin has higher priority than Play's native JPAPlugin.
    //
    if (JPA.entityManagerFactory == null) {
      List<Class> classes = Play.classloader.getAnnotatedClasses(Entity.class);
      if (classes.isEmpty() && Play.configuration.getProperty("jpa.entities", "").equals("")) {
        return;
      }
      if (MDB.datasources == null || MDB.datasources.isEmpty()) {
        if (Play.configuration.getProperty("mjpa.runWithNoDB", "").equals("true")) {
          //
          //	Create a dummy entity manager factory, so that JPA is prevented from screaming.
          //
          JPA.entityManagerFactory = getDummyFactory();
          log.info(
              "No properly configured databases found.  JPA will not be initialized until databases are added");
        } else {
          throw new JPAException(
              "Cannot start a MJPA manager without a properly configured database",
              new NullPointerException("No datasource configured"));
        }
      } else {
        //
        //	Iterate over the datasources and build a configuration for each.
        //
        for (Entry<String, DataSource> entry : MDB.datasources.entrySet()) {
          ComboPooledDataSource datasource = (ComboPooledDataSource) entry.getValue();

          Ejb3Configuration cfg = buildEjbConfiguration(classes, datasource);
          Logger.trace("Initializing JPA ...");
          try {
            EntityManagerFactory factory = cfg.buildEntityManagerFactory();
            JPA.entityManagerFactory = factory;
            factoryMap.put(entry.getKey(), factory);
            log.debug("Added datasource: " + datasource.getJdbcUrl());
          } catch (PersistenceException e) {
            throw new JPAException(e.getMessage(), e.getCause() != null ? e.getCause() : e);
          }
        }
      }
      JPQLDialect.instance = new JPQLDialect();
    }

    //
    //	Set up the key extractor here, by looking for an application class that implements it.
    //
    List<Class> extractors = Play.classloader.getAssignableClasses(RequestDBKeyExtractor.class);
    if (extractors.size() > 1) {
      throw new JPAException(
          "Too many DB Key extract classes.  "
              + "The Multiple DB plugin must use a single extractor class to "
              + "specify its extractor.  These classes where found: "
              + extractors);
    } else if (!extractors.isEmpty()) {
      Class clazz = extractors.get(0);
      try {
        keyExtractor = (RequestDBKeyExtractor) clazz.newInstance();
      } catch (InstantiationException e) {
        log.error("Unable to instantiate extractor class:", e);
      } catch (IllegalAccessException e) {
        log.error("Invalid access to extractor class:", e);
      }
      log.debug("Using application DB key extractor class: " + keyExtractor.getClass().getName());
    } else {
      log.debug("Using default DB key extractor class: " + keyExtractor.getClass().getName());
    }
  }