List of usage examples for javax.persistence Persistence createEntityManagerFactory
public static EntityManagerFactory createEntityManagerFactory(String persistenceUnitName, Map properties)
From source file:org.openhab.persistence.jpa.internal.JpaPersistenceService.java
/** * Creates a new EntityManagerFactory with properties read from openhab.cfg via JpaConfiguration. * @return initialized EntityManagerFactory *//*from w w w . j a v a2 s .co m*/ protected EntityManagerFactory newEntityManagerFactory() { logger.debug("Creating EntityManagerFactory..."); Map<String, String> properties = new HashMap<String, String>(); properties.put("javax.persistence.jdbc.url", JpaConfiguration.dbConnectionUrl); properties.put("javax.persistence.jdbc.driver", JpaConfiguration.dbDriverClass); if (JpaConfiguration.dbUserName != null) { properties.put("javax.persistence.jdbc.user", JpaConfiguration.dbUserName); } if (JpaConfiguration.dbPassword != null) { properties.put("javax.persistence.jdbc.password", JpaConfiguration.dbPassword); } if (JpaConfiguration.dbUserName != null && JpaConfiguration.dbPassword == null) { logger.warn("JPA persistence - it is recommended to use a password to protect data store"); } if (JpaConfiguration.dbSyncMapping != null && !StringUtils.isBlank(JpaConfiguration.dbSyncMapping)) { logger.warn("You are settings openjpa.jdbc.SynchronizeMappings, I hope you know what you're doing!"); properties.put("openjpa.jdbc.SynchronizeMappings", JpaConfiguration.dbSyncMapping); } EntityManagerFactory fac = Persistence.createEntityManagerFactory(getPersistenceUnitName(), properties); logger.debug("Creating EntityManagerFactory...done"); return fac; }
From source file:org.apache.aiaravata.application.catalog.data.util.AppCatalogJPAUtils.java
public static EntityManager getEntityManager() throws ApplicationSettingsException { if (factory == null) { String connectionProperties = "DriverClassName=" + readServerProperties(APPCATALOG_JDBC_DRIVER) + "," + "Url=" + readServerProperties(APPCATALOG_JDBC_URL) + "," + "Username=" + readServerProperties(APPCATALOG_JDBC_USER) + "," + "Password=" + readServerProperties(APPCATALOG_JDBC_PWD); System.out.println(connectionProperties); Map<String, String> properties = new HashMap<String, String>(); properties.put("openjpa.ConnectionDriverName", "org.apache.commons.dbcp.BasicDataSource"); properties.put("openjpa.ConnectionProperties", connectionProperties); properties.put("openjpa.DynamicEnhancementAgent", "true"); properties.put("openjpa.RuntimeUnenhancedClasses", "unsupported"); properties.put("openjpa.DataCache", "true(CacheSize=" + Integer.valueOf(readServerProperties(JPA_CACHE_SIZE)) + ", SoftReferenceSize=0)"); properties.put("openjpa.QueryCache", "true(CacheSize=" + Integer.valueOf(readServerProperties(JPA_CACHE_SIZE)) + ", SoftReferenceSize=0)"); properties.put("openjpa.RemoteCommitProvider", "sjvm"); properties.put("openjpa.Log", "DefaultLevel=INFO, Runtime=INFO, Tool=INFO, SQL=INFO"); properties.put("openjpa.jdbc.SynchronizeMappings", "buildSchema(ForeignKeys=true)"); properties.put("openjpa.jdbc.QuerySQLCache", "false"); factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME, properties); }//from w w w .j av a2 s.co m return factory.createEntityManager(); }
From source file:com.thruzero.domain.jpa.transaction.JpaDatabaseTransactionMgr.java
protected static synchronized EntityManager createEntityManager() { // TODO-p1(george) static synchronized bottleneck if (entityManagerFactory == null) { transactionMgrLogHelper.logCreatingEntityManagerFactory(); entityManagerFactory = Persistence.createEntityManagerFactory(persistenceUnitName, cachedParams); }//from www . j a va 2 s. c o m return entityManagerFactory.createEntityManager(); }
From source file:ox.softeng.burst.service.BurstService.java
public BurstService(Properties properties) throws IOException, TimeoutException, IllegalStateException { logger.info("Starting application version {}", BurstService.class.getPackage().getSpecificationVersion()); // Output env version from potential dockerfile environment if (!Strings.isNullOrEmpty(System.getenv("BURST_VERSION"))) logger.info("Docker container build version {}", System.getenv("BURST_VERSION")); if (!properties.containsKey("burst.database.migration.disabled")) { String user = properties.getProperty("hibernate.connection.user"); String url = properties.getProperty("hibernate.connection.url"); String password = properties.getProperty("hibernate.connection.password"); logger.info("Migrating database using: url: {} user: {} password: ****", url, user); migrateDatabase(url, user, password); }/*from w ww . jav a2 s . com*/ entityManagerFactory = Persistence.createEntityManagerFactory("ox.softeng.burst", properties); serviceChoice = properties.getProperty("burst.service", "all"); switch (serviceChoice) { case "message": createRabbitMessageService(properties); break; case "report": createReportSchedulerService(properties); break; default: createRabbitMessageService(properties); createReportSchedulerService(properties); } }
From source file:org.eclipse.smila.binarystorage.persistence.jpa.JPABinaryPersistence.java
/** * Initialize JPABinaryPersistence.//from ww w. ja va 2s . c om * * @param binaryStorageConfig * BinaryStorageConfiguration * * @throws BinaryStorageException * if any error occurs */ private void init(final BinaryStorageConfiguration binaryStorageConfig) throws BinaryStorageException { EntityManager em = null; try { readConfiguration(); if (!_properties.containsKey("eclipselink.logging.file")) { final File workingDir = WorkspaceHelper.createWorkingDir(BUNDLE_NAME); final File logfile = new File(workingDir, "jpa.log"); _properties.put("eclipselink.logging.file", logfile.getAbsolutePath()); } // set up eclipseLink _emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME, _properties); // create an initial EntityManager to create the database em = _emf.createEntityManager(); } catch (final Exception e) { throw new BinaryStorageException("error activating JPABinaryPersistence", e); } finally { closeEntityManager(em); } if (_log.isTraceEnabled()) { _log.trace("started JPABinaryPersistence"); } }
From source file:name.livitski.tools.persista.StorageBootstrap.java
/** * Creates an entity manager using this object's configuration. * Both {@link UserNameSetting user's name} and her * {@link PasswordSetting password} are read from the * {@link #getConfigFile() configuration file}. * @return new entity manager. The caller is responsible for * {@link EntityManager#close() closing} the entity manager * when it is no longer needed./* w w w. ja v a2s . co m*/ * @throws ConfigurationException if there is a problem * with configuration */ public EntityManager createEntityManager() throws StorageConfigurationException { try { final File configFile = getConfigFile(); // use the default config file if necessary final Configuration config = getConfig(); final UserNameSetting userNameSetting = config.findSetting(UserNameSetting.class); if (!userNameSetting.isSet()) throw new StorageConfigurationException(this, "Required setting '" + userNameSetting.getName() + "' missing from the settings file " + configFile); final PasswordSetting passwordSetting = config.findSetting(PasswordSetting.class); if (!passwordSetting.isSet()) throw new StorageConfigurationException(this, "Required setting '" + passwordSetting.getName() + "' missing from the settings file " + configFile); final String url = jdbcURL(readSetting(DBNameSetting.class)); if (null == persistenceFactory) { Map<String, Object> emfSettings = new TreeMap<String, Object>(); emfSettings.put(AvailableSettings.DIALECT, readSetting(HibernateSQLDialectSetting.class).getName()); emfSettings.put(HibernatePersistence.JDBC_DRIVER, getJDBCDriverClass().getName()); emfSettings.put(HibernatePersistence.JDBC_PASSWORD, passwordSetting.getValue()); emfSettings.put(HibernatePersistence.JDBC_USER, userNameSetting.getValue()); emfSettings.put(HibernatePersistence.JDBC_URL, url); persistenceFactory = Persistence.createEntityManagerFactory(getPersistenceUnit(), emfSettings); } return new EntityManager(persistenceFactory.createEntityManager()); } catch (ConfigurationException badConfig) { throw new StorageConfigurationException(this, badConfig); } }
From source file:org.apache.oozie.service.JPAService.java
/** * Initializes the {@link JPAService}./*from w w w . j av a2 s .com*/ * * @param services services instance. */ public void init(Services services) throws ServiceException { LOG = XLog.getLog(JPAService.class); Configuration conf = services.getConf(); String dbSchema = ConfigurationService.get(conf, CONF_DB_SCHEMA); String url = ConfigurationService.get(conf, CONF_URL); String driver = ConfigurationService.get(conf, CONF_DRIVER); String user = ConfigurationService.get(conf, CONF_USERNAME); String password = ConfigurationService.getPassword(conf, CONF_PASSWORD).trim(); String maxConn = ConfigurationService.get(conf, CONF_MAX_ACTIVE_CONN).trim(); String dataSource = ConfigurationService.get(conf, CONF_CONN_DATA_SOURCE); String connPropsConfig = ConfigurationService.get(conf, CONF_CONN_PROPERTIES); String brokerImplConfig = ConfigurationService.get(conf, CONF_OPENJPA_BROKER_IMPL); boolean autoSchemaCreation = ConfigurationService.getBoolean(conf, CONF_CREATE_DB_SCHEMA); boolean validateDbConn = ConfigurationService.getBoolean(conf, CONF_VALIDATE_DB_CONN); String evictionInterval = ConfigurationService.get(conf, CONF_VALIDATE_DB_CONN_EVICTION_INTERVAL).trim(); String evictionNum = ConfigurationService.get(conf, CONF_VALIDATE_DB_CONN_EVICTION_NUM).trim(); if (!url.startsWith("jdbc:")) { throw new ServiceException(ErrorCode.E0608, url, "invalid JDBC URL, must start with 'jdbc:'"); } String dbType = url.substring("jdbc:".length()); if (dbType.indexOf(":") <= 0) { throw new ServiceException(ErrorCode.E0608, url, "invalid JDBC URL, missing vendor 'jdbc:[VENDOR]:...'"); } dbType = dbType.substring(0, dbType.indexOf(":")); String persistentUnit = "oozie-" + dbType; // Checking existince of ORM file for DB type String ormFile = "META-INF/" + persistentUnit + "-orm.xml"; try { IOUtils.getResourceAsStream(ormFile, -1); } catch (IOException ex) { throw new ServiceException(ErrorCode.E0609, dbType, ormFile); } // support for mysql replication urls "jdbc:mysql:replication://master:port,slave:port[,slave:port]/db" if (url.startsWith("jdbc:mysql:replication")) { url = "\"".concat(url).concat("\""); LOG.info("A jdbc replication url is provided. Url: [{0}]", url); } String connProps = "DriverClassName={0},Url={1},Username={2},Password={3},MaxActive={4}"; connProps = MessageFormat.format(connProps, driver, url, user, password, maxConn); Properties props = new Properties(); if (autoSchemaCreation) { connProps += ",TestOnBorrow=false,TestOnReturn=false,TestWhileIdle=false"; props.setProperty("openjpa.jdbc.SynchronizeMappings", "buildSchema(ForeignKeys=true)"); } else if (validateDbConn) { // validation can be done only if the schema already exist, else a // connection cannot be obtained to create the schema. String interval = "timeBetweenEvictionRunsMillis=" + evictionInterval; String num = "numTestsPerEvictionRun=" + evictionNum; connProps += ",TestOnBorrow=true,TestOnReturn=true,TestWhileIdle=true," + interval + "," + num; connProps += ",ValidationQuery=select count(*) from VALIDATE_CONN"; connProps = MessageFormat.format(connProps, dbSchema); } else { connProps += ",TestOnBorrow=false,TestOnReturn=false,TestWhileIdle=false"; } if (connPropsConfig != null) { connProps += "," + connPropsConfig; } props.setProperty("openjpa.ConnectionProperties", connProps); props.setProperty("openjpa.ConnectionDriverName", dataSource); if (!StringUtils.isEmpty(brokerImplConfig)) { props.setProperty("openjpa.BrokerImpl", brokerImplConfig); LOG.info("Setting openjpa.BrokerImpl to {0}", brokerImplConfig); } factory = Persistence.createEntityManagerFactory(persistentUnit, props); EntityManager entityManager = getEntityManager(); entityManager.find(WorkflowActionBean.class, 1); entityManager.find(WorkflowJobBean.class, 1); entityManager.find(CoordinatorActionBean.class, 1); entityManager.find(CoordinatorJobBean.class, 1); entityManager.find(SLAEventBean.class, 1); entityManager.find(JsonSLAEvent.class, 1); entityManager.find(BundleJobBean.class, 1); entityManager.find(BundleActionBean.class, 1); entityManager.find(SLARegistrationBean.class, 1); entityManager.find(SLASummaryBean.class, 1); LOG.info(XLog.STD, "All entities initialized"); // need to use a pseudo no-op transaction so all entities, datasource // and connection pool are initialized one time only entityManager.getTransaction().begin(); OpenJPAEntityManagerFactorySPI spi = (OpenJPAEntityManagerFactorySPI) factory; // Mask the password with '***' String logMsg = spi.getConfiguration().getConnectionProperties().replaceAll("Password=.*?,", "Password=***,"); LOG.info("JPA configuration: {0}", logMsg); entityManager.getTransaction().commit(); entityManager.close(); try { CodecFactory.initialize(conf); } catch (Exception ex) { throw new ServiceException(ErrorCode.E0100, getClass().getName(), ex); } }
From source file:org.opencms.db.jpa.CmsSqlManager.java
/** * Initialize the static part of the class.<p> * // w ww .ja va2s . c o m * @param config the combined configuration of "opencms.properties" and the "persistence.xml" */ public static void init(CmsParameterConfiguration config) { if (!m_isInitialized) { m_isInitialized = true; String connProps = buildConnectionPropertiesValue(config, CmsDbPool.OPENCMS_DEFAULT_POOL_NAME); Properties systemProps = System.getProperties(); systemProps.setProperty(CmsPersistenceUnitConfiguration.ATTR_CONNECTION_PROPERTIES, connProps); m_persistenceFactory = Persistence.createEntityManagerFactory(JPA_PERSISTENCE_UNIT, systemProps); m_factoryTable.put(JPA_PERSISTENCE_UNIT, m_persistenceFactory); CmsPoolEntityManagerFactory entityMan = new CmsPoolEntityManagerFactory(m_persistenceFactory); int entityManagerPoolSize = config.getInteger(CmsDbPool.KEY_DATABASE_POOL + "." + CmsDbPool.OPENCMS_DEFAULT_POOL_NAME + "." + CmsDbPool.KEY_ENTITY_MANAGER_POOL_SIZE, DEFAULT_ENTITY_MANAGER_POOL_SIZE); m_openCmsEmPool = new StackObjectPool(entityMan, entityManagerPoolSize, 0); } }
From source file:org.apache.wookie.beans.jpa.JPAPersistenceManager.java
/** * Initialize implementation with configuration. * // w w w . j a va 2s .c o m * @param configuration * configuration properties * @param initializeStore * truncate and initialize persistent store */ public static void initialize(Configuration configuration, boolean initializeStore) { try { // configuration cacheSize = configuration.getString(PERSISTENCE_MANAGER_CACHE_SIZE_PROPERTY_NAME); dbType = configuration.getString(PERSISTENCE_MANAGER_DB_TYPE_PROPERTY_NAME); dictionaryType = ((dbType != null) ? DB_TYPE_TO_JPA_DICTIONARY_MAP.get(dbType) : null); if ((dbType != null) && (dictionaryType == null)) { throw new IllegalArgumentException("Unsupported database type: " + dbType); } // initialize persistent store if (initializeStore && (dbType != null)) { // get datasource connection Context initialContext = new InitialContext(); DataSource dataSource = (DataSource) initialContext .lookup(WIDGET_DATABASE_JNDI_DATASOURCE_FULL_NAME); Connection connection = dataSource.getConnection(); connection.setAutoCommit(true); // execute initialization scripts String sqlScriptResource = dbType + "-wookie-schema.sql"; InputStream sqlStream = JPAPersistenceManager.class.getResourceAsStream(sqlScriptResource); if (sqlStream == null) { throw new IllegalArgumentException( "Unsupported persistent store initialization script: " + sqlScriptResource); } SQLScriptReader reader = new SQLScriptReader(sqlStream); int statementCount = 0; int statementErrorCount = 0; for (;;) { String scriptStatement = reader.readSQLStatement(); if (scriptStatement != null) { Statement statement = connection.createStatement(); statementCount++; try { statement.execute(scriptStatement); } catch (SQLException sqle) { statementErrorCount++; } } else { break; } } logger.info("Persistent store initialized from " + sqlScriptResource + ", (" + statementCount + " statements, " + statementErrorCount + " errors)"); // close datasource connection connection.close(); } // initialize entity manager factory Properties persistenceProperties = new Properties(); InputStream propertiesStream = JPAPersistenceManager.class .getResourceAsStream("persistence.properties"); if (propertiesStream == null) { throw new IllegalArgumentException("Unable to load configuration: persistence.properties"); } persistenceProperties.load(propertiesStream); if (cacheSize != null) { int dataCacheSize = Integer.parseInt(cacheSize); persistenceProperties.setProperty("openjpa.DataCache", "true(CacheSize=" + dataCacheSize + ",SoftReferenceSize=0)"); int queryCacheSize = Integer.parseInt(cacheSize) / 10; persistenceProperties.setProperty("openjpa.QueryCache", "CacheSize=" + queryCacheSize + ",SoftReferenceSize=0"); } if (dictionaryType != null) { persistenceProperties.setProperty("openjpa.jdbc.DBDictionary", dictionaryType); } EntityManagerFactory factory = Persistence.createEntityManagerFactory("wookie", persistenceProperties); entityManagerFactory = OpenJPAPersistence.cast(factory); logger.info("Initialized"); } catch (Exception e) { throw new RuntimeException("Unable to initialize 1: " + e, e); } }
From source file:org.drools.semantics.lang.dl.DL_9_CompilationTest.java
private void checkSQLRefresh(Object obj, ClassLoader urlk, String punit) { ClassLoader oldKL = Thread.currentThread().getContextClassLoader(); EntityManagerFactory emf = null;/*w w w.j a va 2 s . c om*/ EntityManager em = null; try { Thread.currentThread().setContextClassLoader(urlk); HashMap props = new HashMap(); props.put("hibernate.hbm2ddl.auto", "create-drop"); emf = Persistence.createEntityManagerFactory(punit, props); em = emf.createEntityManager(); checkJPARefresh(obj, ((UIdAble) obj).getDyEntryId(), em); } finally { Thread.currentThread().setContextClassLoader(oldKL); if (em != null && em.isOpen()) { em.clear(); em.close(); } if (emf != null && emf.isOpen()) { emf.close(); } } }