Пример #1
0
  @Override
  public void onApplicationStart() {

    // must check and configure JPA for each DBConfig
    for (DBConfig dbConfig : DB.getDBConfigs()) {
      // check and enable JPA on this config

      // is JPA already configured?
      String configName = dbConfig.getDBConfigName();

      if (JPA.getJPAConfig(configName, true) == null) {
        // must configure it

        // resolve prefix for hibernate config..
        // should be nothing for default, and db_<name> for others
        String propPrefix = "";
        if (!DBConfig.defaultDbConfigName.equalsIgnoreCase(configName)) {
          propPrefix = "db_" + configName + ".";
        }
        List<Class> classes = findEntityClassesForThisConfig(configName, propPrefix);
        if (classes == null) continue;

        // we're ready to configure this instance of JPA
        final String hibernateDataSource =
            Play.configuration.getProperty(propPrefix + "hibernate.connection.datasource");

        if (StringUtils.isEmpty(hibernateDataSource) && dbConfig == null) {
          throw new JPAException(
              "Cannot start a JPA manager without a properly configured database"
                  + getConfigInfoString(configName),
              new NullPointerException("No datasource configured"));
        }

        Ejb3Configuration cfg = new Ejb3Configuration();

        if (dbConfig.getDatasource() != null) {
          cfg.setDataSource(dbConfig.getDatasource());
        }

        if (!Play.configuration
            .getProperty(propPrefix + "jpa.ddl", Play.mode.isDev() ? "update" : "none")
            .equals("none")) {
          cfg.setProperty(
              "hibernate.hbm2ddl.auto",
              Play.configuration.getProperty(propPrefix + "jpa.ddl", "update"));
        }

        String driver = null;
        if (StringUtils.isEmpty(propPrefix)) {
          driver = Play.configuration.getProperty("db.driver");
        } else {
          driver = Play.configuration.getProperty(propPrefix + "driver");
        }
        cfg.setProperty("hibernate.dialect", getDefaultDialect(propPrefix, driver));
        cfg.setProperty("javax.persistence.transaction", "RESOURCE_LOCAL");

        cfg.setInterceptor(new PlayInterceptor());

        // This setting is global for all JPAs - only configure if configuring default JPA
        if (StringUtils.isEmpty(propPrefix)) {
          if (Play.configuration.getProperty(propPrefix + "jpa.debugSQL", "false").equals("true")) {
            org.apache.log4j.Logger.getLogger("org.hibernate.SQL").setLevel(Level.ALL);
          } else {
            org.apache.log4j.Logger.getLogger("org.hibernate.SQL").setLevel(Level.OFF);
          }
        }
        // inject additional  hibernate.* settings declared in Play! configuration
        Properties additionalProperties =
            (Properties)
                Utils.Maps.filterMap(Play.configuration, "^" + propPrefix + "hibernate\\..*");
        // We must remove prefix from names
        Properties transformedAdditionalProperties = new Properties();
        for (Map.Entry<Object, Object> entry : additionalProperties.entrySet()) {
          Object key = entry.getKey();
          if (!StringUtils.isEmpty(propPrefix)) {
            key = ((String) key).substring(propPrefix.length()); // chop off the prefix
          }
          transformedAdditionalProperties.put(key, entry.getValue());
        }
        cfg.addProperties(transformedAdditionalProperties);

        try {
          // nice hacking :) I like it..
          Field field = cfg.getClass().getDeclaredField("overridenClassLoader");
          field.setAccessible(true);
          field.set(cfg, Play.classloader);
        } catch (Exception e) {
          Logger.error(
              e, "Error trying to override the hibernate classLoader (new hibernate version ???)");
        }

        for (Class<?> clazz : classes) {
          cfg.addAnnotatedClass(clazz);
          if (Logger.isTraceEnabled()) {
            Logger.trace("JPA Model : %s", clazz);
          }
        }
        String[] moreEntities =
            Play.configuration.getProperty(propPrefix + "jpa.entities", "").split(", ");
        for (String entity : moreEntities) {
          if (entity.trim().equals("")) {
            continue;
          }
          try {
            cfg.addAnnotatedClass(Play.classloader.loadClass(entity));
          } catch (Exception e) {
            Logger.warn("JPA -> Entity not found: %s", entity);
          }
        }

        for (ApplicationClass applicationClass : Play.classes.all()) {
          if (applicationClass.isClass() || applicationClass.javaPackage == null) {
            continue;
          }
          Package p = applicationClass.javaPackage;
          Logger.info("JPA -> Adding package: %s", p.getName());
          cfg.addPackage(p.getName());
        }

        String mappingFile = Play.configuration.getProperty(propPrefix + "jpa.mapping-file", "");
        if (mappingFile != null && mappingFile.length() > 0) {
          cfg.addResource(mappingFile);
        }

        if (Logger.isTraceEnabled()) {
          Logger.trace("Initializing JPA" + getConfigInfoString(configName) + " ...");
        }

        try {
          JPA.addConfiguration(configName, cfg);
        } catch (PersistenceException e) {
          throw new JPAException(
              e.getMessage() + getConfigInfoString(configName),
              e.getCause() != null ? e.getCause() : e);
        }
      }
    }

    // must look for Entity-objects referring to none-existing JPAConfig
    List<Class> allEntityClasses = Play.classloader.getAnnotatedClasses(Entity.class);
    for (Class clazz : allEntityClasses) {
      String configName = Entity2JPAConfigResolver.getJPAConfigNameForEntityClass(clazz);
      if (JPA.getJPAConfig(configName, true) == null) {
        throw new JPAException(
            "Found Entity-class ("
                + clazz.getName()
                + ") referring to none-existing JPAConfig"
                + getConfigInfoString(configName)
                + ". "
                + "Is JPA properly configured?");
      }
    }
  }
Пример #2
0
  public void importColumns() throws Exception {
    LOGGER.info("List of objects for source: " + stageSourceCode);
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("OpenBIStage");
    EntityManager em = emf.createEntityManager();
    Query query;

    // get source
    query = em.createQuery("SELECT x FROM StageSource x WHERE x.etlStageSourceCode = ?1");
    query.setParameter(1, stageSourceCode);
    List<StageSource> sources = query.getResultList();

    // get source objects and dbs
    List<StageObject> objects = sources.get(0).getStageObject();
    List<StageSourceDb> sourcedbs = sources.get(0).getStageSourceDb();

    // load properties from property file
    String dbpropertyfile =
        "datasources/" + sourcedbs.get(0).getEtlStageSourceDbJdbcname() + ".properties";
    Properties dbproperties = new Properties();
    dbproperties.load(new FileInputStream(dbpropertyfile));

    // Configure db connection
    org.opendatakraken.core.db.DBConnection sourceConnectionBean =
        new org.opendatakraken.core.db.DBConnection();
    sourceConnectionBean.setPropertyFile(dbproperties.getProperty("srcconnaddpropertyfile"));
    sourceConnectionBean.setDatabaseDriver(dbproperties.getProperty("srcdbdriverclass"));
    sourceConnectionBean.setConnectionURL(dbproperties.getProperty("srcdbconnectionurl"));
    sourceConnectionBean.setUserName(dbproperties.getProperty("srcdbusername"));
    sourceConnectionBean.setPassWord(dbproperties.getProperty("srcdbpassword"));
    sourceConnectionBean.openConnection();

    DictionaryExtractor dataDict = new DictionaryExtractor();
    dataDict.setSourceConnection(sourceConnectionBean);

    // For each object
    String sourceIdentifier;
    for (StageObject object : objects) {

      // Dermine source identifier
      sourceIdentifier = object.getEtlStageObjectName();
      if (!(sourcedbs.get(0).getEtlStageSourceOwner().equals(""))
          && sourcedbs.get(0).getEtlStageSourceOwner() != null) {
        sourceIdentifier = sourcedbs.get(0).getEtlStageSourceOwner() + "." + sourceIdentifier;
      }

      dataDict.setSourceTable(sourceIdentifier);
      dataDict.retrieveColumns();

      String[] colNames = dataDict.getColumnNames();
      String[] colDefs = dataDict.getColumnDefinition();
      String[] colOriginalDefs = dataDict.getColumnDefinition();
      int[] colPkPos = dataDict.getColumnPkPositions();

      em.getTransaction().begin();

      for (int i = 0; i < colNames.length; i++) {
        query =
            em.createQuery(
                "SELECT x FROM StageColumn x WHERE x.etlStageObjectId = ?1 AND x.etlStageColumnName = ?2");
        query.setParameter(1, object.getEtlStageObjectId());
        query.setParameter(2, colNames[i]);
        List<StageColumn> columns = query.getResultList();

        StageColumn column;
        if (columns.size() == 0) {
          column = new StageColumn();
          column.setEtlStageObjectId(BigDecimal.valueOf(object.getEtlStageObjectId()));
          column.setEtlStageColumnPos(BigDecimal.valueOf(i + 1));
          column.setEtlStageColumnName(colNames[i]);
          column.setEtlStageColumnDef(colDefs[i]);
          column.setEtlStageColumnDefSrc(colOriginalDefs[i]);
          column.setEtlStageColumnEdwhFlag(BigDecimal.valueOf(1));
          if (colPkPos[i] > 0) {
            column.setEtlStageColumnNkPos(BigDecimal.valueOf(colPkPos[i]));
            object.setEtlStageSourceNkFlag(BigDecimal.valueOf(1));
          }
          em.persist(column);
        } else {
          column = columns.get(0);
          column.setEtlStageColumnPos(BigDecimal.valueOf(i + 1));
          column.setEtlStageColumnDef(colDefs[i]);
          column.setEtlStageColumnDefSrc(colOriginalDefs[i]);
          if (colPkPos[i] > 0) {
            column.setEtlStageColumnNkPos(BigDecimal.valueOf(colPkPos[i]));
            object.setEtlStageSourceNkFlag(BigDecimal.valueOf(1));
          }
        }
      }
      em.getTransaction().commit();
    }
  }