Example usage for javax.persistence Persistence createEntityManagerFactory

List of usage examples for javax.persistence Persistence createEntityManagerFactory

Introduction

In this page you can find the example usage for javax.persistence Persistence createEntityManagerFactory.

Prototype

public static EntityManagerFactory createEntityManagerFactory(String persistenceUnitName, Map properties) 

Source Link

Document

Create and return an EntityManagerFactory for the named persistence unit using the given properties.

Usage

From source file:org.sakaiproject.kernel.persistence.eclipselink.EntityManagerFactoryProvider.java

/**
 * Construct an EclipseLink entity manager provider.
 *
 * @param minRead//from   ww w . ja  v  a 2s .c  o  m
 * @param minWrite
 * @param dataSourceService
 * @param unitName
 */
@Inject
@SuppressWarnings(value = {
        "DP_CREATE_CLASSLOADER_INSIDE_DO_PRIVILEGED" }, justification = "Expected to only ever be executed from a privalaged environment")
public EntityManagerFactoryProvider(DataSourceService dataSourceService,
        @Named(KernelConstants.DB_MIN_NUM_READ) String minRead,
        @Named(KernelConstants.DB_MIN_WRITE) String minWrite,
        @Named(KernelConstants.DB_UNITNAME) String unitName,
        @Named(KernelConstants.JDBC_DRIVER_NAME) String driverClassName,
        @Named(KernelConstants.JDBC_URL) String url, @Named(KernelConstants.JDBC_USERNAME) String username,
        @Named(KernelConstants.JDBC_PASSWORD) String password) {

    Map<String, Object> properties = new HashMap<String, Object>();

    // Ensure RESOURCE_LOCAL transactions is used.
    properties.put(TRANSACTION_TYPE, PersistenceUnitTransactionType.RESOURCE_LOCAL.name());

    LOG.info("Using provided data source");
    properties.put(dataSourceService.getType(), dataSourceService.getDataSource());

    // Configure the internal EclipseLink connection pool
    // LOG.info("Creating internal data source");
    // properties.put(PersistenceUnitProperties.JDBC_DRIVER, driverClassName);
    // properties.put(PersistenceUnitProperties.JDBC_URL, url);
    // properties.put(PersistenceUnitProperties.JDBC_USER, username);
    // properties.put(PersistenceUnitProperties.JDBC_PASSWORD, password);
    // properties
    // .put(PersistenceUnitProperties.JDBC_READ_CONNECTIONS_MIN, minRead);
    // properties.put(PersistenceUnitProperties.JDBC_WRITE_CONNECTIONS_MIN,
    // minWrite);

    // Configure logging. FINE ensures all SQL is shown
    properties.put(LOGGING_LEVEL, (debug ? "FINE" : "INFO"));
    properties.put(LOGGING_TIMESTAMP, "true");
    properties.put(LOGGING_THREAD, "true");
    properties.put(LOGGING_SESSION, "true");

    // Ensure that no server-platform is configured
    properties.put(TARGET_SERVER, TargetServer.None);

    properties.put(PersistenceUnitProperties.DDL_GENERATION, PersistenceUnitProperties.CREATE_ONLY);
    properties.put(PersistenceUnitProperties.DROP_JDBC_DDL_FILE, "drop.sql");
    properties.put(PersistenceUnitProperties.CREATE_JDBC_DDL_FILE, "create.sql");
    properties.put(PersistenceUnitProperties.DDL_GENERATION_MODE,
            PersistenceUnitProperties.DDL_BOTH_GENERATION);

    // properties.put(PersistenceUnitProperties.SESSION_CUSTOMIZER,
    // EnableIntegrityChecker.class.getName());

    LOG.info("Starting connection manager with properties " + properties);
    final Thread currentThread = Thread.currentThread();
    final ClassLoader saveClassLoader = currentThread.getContextClassLoader();

    PersistenceUnitClassLoader persistenceCL = new PersistenceUnitClassLoader(this.getClass().getClassLoader());
    currentThread.setContextClassLoader(persistenceCL);
    entityManagerFactory = Persistence.createEntityManagerFactory(unitName, properties);
    currentThread.setContextClassLoader(saveClassLoader);

}

From source file:io.symcpe.hendrix.api.ApplicationManager.java

public void init(AppConfig appConfiguration) {
    config = new Properties(System.getProperties());
    if (System.getenv(PROP_CONFIG_FILE) != null) {
        try {//w w  w .j a  va2  s.  c o m
            config.load(new FileInputStream(System.getenv(PROP_CONFIG_FILE)));
        } catch (IOException e) {
            throw new RuntimeException("Configuration file not loaded", e);
        }
    } else if (System.getProperty(PROP_CONFIG_FILE) != null) {
        try {
            config.load(new FileInputStream(System.getProperty(PROP_CONFIG_FILE)));
        } catch (IOException e) {
            throw new RuntimeException("Configuration file not loaded", e);
        }
    } else {
        try {
            config.load(
                    ApplicationManager.class.getClassLoader().getResourceAsStream("default-config.properties"));
        } catch (IOException e) {
            throw new RuntimeException("Default configuration file not loaded", e);
        }
    }
    try {
        Utils.createDatabase(config.getProperty(JAVAX_PERSISTENCE_JDBC_URL),
                config.getProperty(JAVAX_PERSISTENCE_JDBC_DB, "hendrix"),
                config.getProperty(JAVAX_PERSISTENCE_JDBC_USER),
                config.getProperty(JAVAX_PERSISTENCE_JDBC_PASSWORD),
                config.getProperty(JAVAX_PERSISTENCE_JDBC_DRIVER));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    config.setProperty(JAVAX_PERSISTENCE_JDBC_URL, config.getProperty(JAVAX_PERSISTENCE_JDBC_URL)
            + config.getProperty(JAVAX_PERSISTENCE_JDBC_DB, "hendrix"));
    factory = Persistence.createEntityManagerFactory("hendrix", config);
    EntityManager em = factory.createEntityManager();
    System.out.println("Rules stats" + em.createNamedQuery("Rules.stats").getResultList());
    em.close();
    if (!LOCAL) {
        initKafkaConnection();
    }
}

From source file:org.isatools.isatab.commandline.PersistenceShellCommand.java

/**
 * TODO: this is a patch used until we are able to make the auto-indexing upon load feature working
 * It is called after persistence.//  www  .j a  v a  2s.  c o m
 *
 * @param store               must contain the studies that have to be reindexed (with proper accession).
 * @param hibernateProperties - The hibernate properties indicating DB properties and Index location/Strategy,
 *                            and so forth.
 */
public static void reindexStudies(BIIObjectStore store, Properties hibernateProperties) {
    // Need to initialize this here, otherwise above config will fail
    log = Logger.getLogger(PersistenceShellCommand.class);

    hibernateProperties.setProperty("hibernate.search.indexing_strategy", "event");
    hibernateProperties.setProperty("hibernate.hbm2ddl.auto", "update");
    hibernateProperties.setProperty("hbm2ddl.drop", "false");

    EntityManagerFactory emf1 = Persistence.createEntityManagerFactory("BIIEntityManager", hibernateProperties);
    EntityManager entityManager1 = emf1.createEntityManager();

    StudyDAO studyDAO = DaoFactory.getInstance(entityManager1).getStudyDAO();
    FullTextEntityManager fullTxtEm = Search.getFullTextEntityManager(entityManager1);
    EntityTransaction tnx = entityManager1.getTransaction();

    tnx.begin();
    for (Study study : store.valuesOfType(Study.class)) {
        Study dbStudy = studyDAO.getByAcc(study.getAcc());
        if (dbStudy != null) {
            out.println("Indexing Study #" + dbStudy.getAcc());
            fullTxtEm.index(dbStudy);
            log.info("Indexing of Study # " + dbStudy.getAcc() + " is complete!");
        }

    }
    log.info("Commiting & closing Entity Manager.");
    tnx.commit();
    entityManager1.close();
}

From source file:com.sun.socialsite.business.EmfProvider.java

/**
 * Called once (and only once) to find and initialize our EMF.
 *///  w  w w .  ja v  a 2s.  com
private static EntityManagerFactory initEmf() throws SocialSiteException {

    String jpaConfigurationType = Config.getProperty("jpa.configurationType");
    log.info("jpaConfigurationType=" + jpaConfigurationType);

    if ("jndi".equals(jpaConfigurationType)) {

        String emfJndiName = "java:comp/env/" + Config.getProperty("jpa.emf.jndi.name");
        log.info("emfJndiName=" + emfJndiName);
        try {
            return (EntityManagerFactory) new InitialContext().lookup(emfJndiName);
        } catch (NamingException e) {
            throw new SocialSiteException("Could not look up EntityManagerFactory in jndi at " + emfJndiName,
                    e);
        }

    } else {

        DatabaseProvider dbProvider = Startup.getDatabaseProvider();

        // Pull in any settings defined in our EMF properties file
        Properties emfProps = loadPropertiesFromResourceName(EMF_PROPS, getContextClassLoader());

        // Add all OpenJPA and Toplinks properties found in Config
        for (String key : Config.keySet()) {
            if (key.startsWith("openjpa.") || key.startsWith("toplink.")) {
                String value = Config.getProperty(key);
                log.info(key + ": " + value);
                emfProps.setProperty(key, value);
            }
        }

        if (dbProvider.getType() == DatabaseProvider.ConfigurationType.JNDI_NAME) {

            // We're doing JNDI, so set OpenJPA JNDI name property
            String jndiName = "java:comp/env/" + dbProvider.getJndiName();
            emfProps.setProperty("openjpa.ConnectionFactoryName", jndiName);

        } else {

            // So set JDBC properties for OpenJPA
            emfProps.setProperty("openjpa.ConnectionDriverName", dbProvider.getJdbcDriverClass());
            emfProps.setProperty("openjpa.ConnectionURL", dbProvider.getJdbcConnectionURL());
            emfProps.setProperty("openjpa.ConnectionUserName", dbProvider.getJdbcUsername());
            emfProps.setProperty("openjpa.ConnectionPassword", dbProvider.getJdbcPassword());

            // And Toplink JPA
            emfProps.setProperty("eclipselink.jdbc.driver", dbProvider.getJdbcDriverClass());
            emfProps.setProperty("eclipselink.jdbc.url", dbProvider.getJdbcConnectionURL());
            emfProps.setProperty("eclipselink.jdbc.user", dbProvider.getJdbcUsername());
            emfProps.setProperty("eclipselink.jdbc.password", dbProvider.getJdbcPassword());

            // And Toplink JPA
            emfProps.setProperty("toplink.jdbc.driver", dbProvider.getJdbcDriverClass());
            emfProps.setProperty("toplink.jdbc.url", dbProvider.getJdbcConnectionURL());
            emfProps.setProperty("toplink.jdbc.user", dbProvider.getJdbcUsername());
            emfProps.setProperty("toplink.jdbc.password", dbProvider.getJdbcPassword());

            // And Hibernate JPA
            emfProps.setProperty("hibernate.connection.driver_class", dbProvider.getJdbcDriverClass());
            emfProps.setProperty("hibernate.connection.url", dbProvider.getJdbcConnectionURL());
            emfProps.setProperty("hibernate.connection.username", dbProvider.getJdbcUsername());
            emfProps.setProperty("hibernate.connection.password", dbProvider.getJdbcPassword());
        }

        try {
            String puName = Config.getProperty("socialsite.puname", "SocialSite_PU");
            return Persistence.createEntityManagerFactory(puName, emfProps);
        } catch (PersistenceException pe) {
            log.error("Failed to create entity manager", pe);
            throw new SocialSiteException(pe);
        }

    }

}

From source file:com.enioka.jqm.api.HibernateClient.java

private EntityManagerFactory createFactory() {
    jqmlogger.debug("Creating connection pool to database");

    InputStream fis = null;/*from   w ww .j av a 2  s  .c  om*/
    try {
        fis = this.getClass().getClassLoader().getResourceAsStream("META-INF/jqm.properties");
        if (fis == null) {
            jqmlogger.trace("No jqm.properties file found.");
        } else {
            p.load(fis);
            jqmlogger.trace("A jqm.properties file was found");
        }
    } catch (IOException e) {
        // We allow no configuration files, but not an unreadable configuration file.
        throw new JqmClientException("META-INF/jqm.properties file is invalid", e);
    } finally {
        closeQuietly(fis);
    }

    EntityManagerFactory newEmf = null;
    if (p.containsKey("javax.persistence.nonJtaDataSource")) {
        // This is a hack. Some containers will use root context as default for JNDI (WebSphere, Glassfish...), other will use
        // java:/comp/env/ (Tomcat...). So if we actually know the required alias, we try both, and the user only has to provide a
        // root JNDI alias that will work in both cases.
        try {
            newEmf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, p);
            // Do a stupid query to force EMF initialization
            EntityManager em = newEmf.createEntityManager();
            em.createQuery("SELECT n from Node n WHERE 1=0").getResultList().size();
            em.close();
        } catch (RuntimeException e) {
            if (e.getCause() != null && e.getCause().getCause() != null
                    && e.getCause().getCause() instanceof NameNotFoundException) {
                jqmlogger.debug("JNDI alias " + p.getProperty("javax.persistence.nonJtaDataSource")
                        + " was not found. Trying with java:/comp/env/ prefix");
                p.setProperty("javax.persistence.nonJtaDataSource",
                        "java:/comp/env/" + p.getProperty("javax.persistence.nonJtaDataSource"));
                newEmf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, p);
                // Do a stupid query to force EMF initialization
                EntityManager em = newEmf.createEntityManager();
                em.createQuery("SELECT n from Node n WHERE 1=3").getResultList().size();
                em.close();
            } else {
                throw e;
            }
        }
    } else {
        newEmf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, p);
    }
    return newEmf;
}

From source file:org.apache.ranger.audit.destination.DBAuditDestination.java

protected void connect() {
    if (isDbConnected()) {
        return;//from ww w . ja va  2 s.c o  m
    }
    try {
        jdbcDriver = MiscUtil.getStringProperty(props, propPrefix + "." + PROP_DB_JDBC_DRIVER);
        jdbcURL = MiscUtil.getStringProperty(props, propPrefix + "." + PROP_DB_JDBC_URL);
        dbUser = MiscUtil.getStringProperty(props, propPrefix + "." + PROP_DB_USER);
        String dbPasswordFromProp = MiscUtil.getStringProperty(props, propPrefix + "." + PROP_DB_PASSWORD);
        String tmpAlias = MiscUtil.getStringProperty(props, propPrefix + "." + PROP_DB_PASSWORD_ALIAS);
        dbPasswordAlias = tmpAlias != null ? tmpAlias : dbPasswordAlias;
        String credFile = MiscUtil.getStringProperty(props, AUDIT_DB_CREDENTIAL_PROVIDER_FILE);

        if (jdbcDriver == null || jdbcDriver.isEmpty()) {
            logger.fatal(
                    "JDBC driver not provided. Set property name " + propPrefix + "." + PROP_DB_JDBC_DRIVER);
            return;
        }
        if (jdbcURL == null || jdbcURL.isEmpty()) {
            logger.fatal("JDBC URL not provided. Set property name " + propPrefix + "." + PROP_DB_JDBC_URL);
            return;
        }
        if (dbUser == null || dbUser.isEmpty()) {
            logger.fatal("DB user not provided. Set property name " + propPrefix + "." + PROP_DB_USER);
            return;
        }
        String dbPassword = MiscUtil.getCredentialString(credFile, dbPasswordAlias);

        if (dbPassword == null || dbPassword.isEmpty()) {
            // If password is not in credential store, let's try password
            // from property
            dbPassword = dbPasswordFromProp;
        }

        if (dbPassword == null || dbPassword.isEmpty()) {
            logger.warn("DB password not provided. Will assume it is empty and continue");
        }
        logger.info("JDBC Driver=" + jdbcDriver + ", JDBC URL=" + jdbcURL + ", dbUser=" + dbUser
                + ", passwordAlias=" + dbPasswordAlias + ", credFile=" + credFile + ", usingPassword="
                + (dbPassword == null ? "no" : "yes"));

        Map<String, String> dbProperties = new HashMap<String, String>();
        dbProperties.put("javax.persistence.jdbc.driver", jdbcDriver);
        dbProperties.put("javax.persistence.jdbc.url", jdbcURL);
        dbProperties.put("javax.persistence.jdbc.user", dbUser);
        if (dbPassword != null) {
            dbProperties.put("javax.persistence.jdbc.password", dbPassword);
        }

        entityManagerFactory = Persistence.createEntityManagerFactory("xa_server", dbProperties);

        logger.info("entityManagerFactory=" + entityManagerFactory);

        daoManager = new DaoManager();
        daoManager.setEntityManagerFactory(entityManagerFactory);

        // this forces the connection to be made to DB
        if (daoManager.getEntityManager() == null) {
            logger.error("Error connecting audit database. EntityManager is null. dbURL=" + jdbcURL
                    + ", dbUser=" + dbUser);
        } else {
            logger.info("Connected to audit database. dbURL=" + jdbcURL + ", dbUser=" + dbUser);
        }

    } catch (Throwable t) {
        logger.error("Error connecting audit database. dbURL=" + jdbcURL + ", dbUser=" + dbUser, t);
    }
}

From source file:org.apache.james.modules.mailbox.JPAMailboxModule.java

@Provides
@Singleton/*from w w w .j  a v  a 2  s .  c  om*/
public EntityManagerFactory provideEntityManagerFactory(JPAConfiguration jpaConfiguration) {
    HashMap<String, String> properties = new HashMap<String, String>();

    properties.put("openjpa.ConnectionDriverName", jpaConfiguration.getDriverName());
    properties.put("openjpa.ConnectionURL", jpaConfiguration.getDriverURL());

    return Persistence.createEntityManagerFactory("Global", properties);

}

From source file:org.apache.ranger.audit.provider.DbAuditProvider.java

private synchronized boolean init() {
    long now = System.currentTimeMillis();

    if ((now - mLastDbFailedTime) < mDbRetryMinIntervalMs) {
        return false;
    }/*from w w w . ja  v a2s . co  m*/

    LOG.info("DbAuditProvider: init()");
    LOG.info("java.library.path:" + System.getProperty("java.library.path"));
    try {
        entityManagerFactory = Persistence.createEntityManagerFactory("xa_server", mDbProperties);

        daoManager = new DaoManager();
        daoManager.setEntityManagerFactory(entityManagerFactory);

        daoManager.getEntityManager(); // this forces the connection to be made to DB
    } catch (Exception excp) {
        logDbError("DbAuditProvider: DB initalization failed", excp);

        cleanUp();

        return false;
    }

    return true;
}

From source file:de.micromata.genome.jpa.EmgrFactory.java

/**
 * Creates a new Emgr object./*from w  ww  .  j  av a  2  s  .  c o m*/
 *
 * @param unitName the unit name
 * @return the entity manager factory
 */
public EntityManagerFactory createEntityManagerFactory(String unitName) {
    Map<String, Object> lsMap = getInitEntityManagerFactoryProperties();
    EntityManagerFactory emf = Persistence.createEntityManagerFactory(unitName, lsMap);
    return emf;
}

From source file:org.efaps.bpm.BPM.java

/**
 * Initialize BPM./*from w  w  w.  j a va  2s .c o  m*/
 *
 * @throws EFapsException on error
 */
public static void initialize() throws EFapsException {
    final SystemConfiguration config = EFapsSystemConfiguration.get();
    final boolean active = config != null ? config.getAttributeValueAsBoolean(KernelSettings.ACTIVATE_BPM)
            : false;
    if (active) {

        if (BPM.PMANAGER != null) {
            BPM.PMANAGER.close();
            BPM.PMANAGER = null;
        }
        if (BPM.SMANAGER != null) {
            BPM.SMANAGER.close();
            BPM.SMANAGER = null;
        }

        UserTransaction userTrans = null;
        InitialContext context = null;
        try {
            context = new InitialContext();
            userTrans = TransactionHelper.findUserTransaction();
            Object object = null;
            try {
                object = context.lookup(JtaTransactionManager.DEFAULT_USER_TRANSACTION_NAME);
            } catch (final NamingException ex) {
                BPM.LOG.info("Checked for JtaTransactionManager");
            }
            if (object == null) {
                context.bind(JtaTransactionManager.DEFAULT_USER_TRANSACTION_NAME, userTrans);
                context.bind(JtaTransactionManager.FALLBACK_TRANSACTION_MANAGER_NAMES[0],
                        TransactionHelper.findTransactionManager());
            }
        } catch (final NamingException ex) {
            BPM.LOG.error("Could not initialise JNDI InitialContext", ex);
        }

        // register our own KnowledgeBuilderFactoryService
        ServiceRegistryImpl.getInstance().addDefault(KnowledgeBuilderFactoryService.class,
                KnowledgeBuilderFactoryServiceImpl.class.getName());

        final RegisterableItemsFactoryImpl itemsFactory = new RegisterableItemsFactoryImpl();
        itemsFactory.addWorkItemHandler("Manual Task", ManualTaskItemHandler.class);
        itemsFactory.addProcessListener(WorkingMemoryLogListener.class);

        final Map<String, String> properties = new HashMap<String, String>();
        properties.put(AvailableSettings.DIALECT, Context.getDbType().getHibernateDialect());
        properties.put(AvailableSettings.SHOW_SQL, String.valueOf(BPM.LOG.isDebugEnabled()));
        properties.put(AvailableSettings.FORMAT_SQL, "true");
        properties.put(AvailableSettings.RELEASE_CONNECTIONS, "after_transaction");
        properties.put(AvailableSettings.CONNECTION_PROVIDER, ConnectionProvider.class.getName());
        properties.put(org.hibernate.jpa.AvailableSettings.NAMING_STRATEGY, NamingStrategy.class.getName());

        final EntityManagerFactory emf = Persistence.createEntityManagerFactory("org.jbpm.persistence.jpa",
                properties);

        final RuntimeEnvironmentBuilder builder = RuntimeEnvironmentBuilder.getDefault()
                .classLoader(EFapsClassLoader.getInstance()).userGroupCallback(new UserGroupCallbackImpl())
                .entityManagerFactory(emf).registerableItemsFactory(itemsFactory).persistence(true)
                .addEnvironmentEntry("TRANSACTION_LOCK_ENABLED", "false");

        BPM.add2EnvironmentBuilder(builder);

        final RuntimeEnvironment environment = builder.get();
        final ManagerFactoryImpl factory = new ManagerFactoryImpl();

        BPM.PMANAGER = factory.newPerProcessInstanceRuntimeManager(environment);
        BPM.SMANAGER = factory.newSingletonRuntimeManager(environment);
    }
}