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:io.symcpe.hendrix.api.dao.TestRulesManager.java

@BeforeClass
public static void beforeClass() throws Exception {
    java.util.logging.Logger.getLogger("org.hibernate").setLevel(Level.OFF);
    Properties config = new Properties(System.getProperties());
    File db = new File(TARGET_RULES_DB);
    if (db.exists()) {
        FileUtils.deleteDirectory(db);/*w w  w .jav  a 2 s .  c o m*/
    }
    config.setProperty("javax.persistence.jdbc.url", CONNECTION_STRING);
    try {
        emf = Persistence.createEntityManagerFactory("hendrix", config);
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }

    EntityManager em = emf.createEntityManager();

    Tenant tenant = new Tenant();
    tenant.setTenant_id(TENANT_ID_1);
    tenant.setTenant_name(TEST_TENANT);
    TenantManager.getInstance().createTenant(em, tenant);

    tenant = new Tenant();
    tenant.setTenant_id(TENANT_ID_2);
    tenant.setTenant_name(TEST_TENANT);
    TenantManager.getInstance().createTenant(em, tenant);

    tenant = new Tenant();
    tenant.setTenant_id(TENANT_ID_3);
    tenant.setTenant_name(TEST_TENANT);
    TenantManager.getInstance().createTenant(em, tenant);

    tenant = new Tenant();
    tenant.setTenant_id(TENANT_ID_5);
    tenant.setTenant_name(TEST_TENANT);
    TenantManager.getInstance().createTenant(em, tenant);

    em.close();
}

From source file:org.apache.airavata.registry.core.workflow.catalog.utils.WorkflowCatalogJPAUtils.java

public static EntityManager getEntityManager() throws ApplicationSettingsException {
    if (factory == null) {
        String connectionProperties = "DriverClassName=" + readServerProperties(WFCATALOG_JDBC_DRIVER) + ","
                + "Url=" + readServerProperties(WFCATALOG_JDBC_URL) + "?autoReconnect=true," + "Username="
                + readServerProperties(WFCATALOG_JDBC_USER) + "," + "Password="
                + readServerProperties(WFCATALOG_JDBC_PASSWORD) + ",validationQuery="
                + readServerProperties(WFCATALOG_VALIDATION_QUERY);
        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");
        // For app catalog, we don't need caching
        //            properties.put("openjpa.DataCache","" + readServerProperties(JPA_CACHE_ENABLED) + "(CacheSize=" + Integer.valueOf(readServerProperties(JPA_CACHE_SIZE)) + ", SoftReferenceSize=0)");
        //            properties.put("openjpa.QueryCache","" + readServerProperties(JPA_CACHE_ENABLED) + "(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");
        properties.put("openjpa.ConnectionFactoryProperties",
                "PrettyPrint=true, PrettyPrintLineLength=72, PrintParameters=true, MaxActive=10, MaxIdle=5, MinIdle=2, MaxWait=31536000,  autoReconnect=true");
        factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME, properties);
    }/*from  ww w .  j  a va 2  s. c  o m*/
    wfCatEntityManager = factory.createEntityManager();
    return wfCatEntityManager;
}

From source file:nl.b3p.viewer.util.TestUtil.java

/**
 * initialisatie van EntityManager {@link #entityManager} en starten
 * transactie.//from ww  w  . ja va2 s . c  om
 *
 * @throws Exception if any
 *
 * @see #entityManager
 */
@Before
public void setUp() throws Exception {
    final String persistenceUnit = System.getProperty("test.persistence.unit");
    Map config = new HashMap();
    String testname = testName.getMethodName();
    testname = testname.replaceAll(":", "-");
    testname = testname.replaceAll(" ", "");
    String randomizer = RandomStringUtils.randomAlphabetic(8);
    config.put("javax.persistence.jdbc.url",
            "jdbc:hsqldb:file:./target/unittest-hsqldb_" + testname + "_" + randomizer + "/db;shutdown=true");
    entityManager = Persistence.createEntityManagerFactory(persistenceUnit, config).createEntityManager();
    if (!entityManager.getTransaction().isActive()) {
        entityManager.getTransaction().begin();
    }
    loadTestData();

    if (!entityManager.getTransaction().isActive()) {
        entityManager.getTransaction().begin();
    }
}

From source file:ox.softeng.burst.services.BurstService.java

public BurstService(Properties properties) {

    logger.info("Starting application version {}", System.getProperty("applicationVersion"));

    // Output env version from potential dockerfile environment
    if (System.getenv("BURST_VERSION") != null)
        logger.info("Docker container build version {}", System.getenv("BURST_VERSION"));

    String user = (String) properties.get("hibernate.connection.user");
    String url = (String) properties.get("hibernate.connection.url");
    String password = (String) properties.get("hibernate.connection.password");

    logger.info("Migrating database using: \n" + "  url: {}" + "  user: {}" + "  password: ****", url, user);
    migrateDatabase(url, user, password);
    entityManagerFactory = Persistence.createEntityManagerFactory("ox.softeng.burst", properties);

    String rabbitMQHost = properties.getProperty("rabbitmq.host");
    String rabbitMQExchange = properties.getProperty("rabbitmq.exchange");
    String rabbitMQQueue = properties.getProperty("rabbitmq.queue");
    String rabbitPortStr = properties.getProperty("rabbitmq.port");
    String rabbitUser = properties.getProperty("rabbitmq.user", ConnectionFactory.DEFAULT_USER);
    String rabbitPassword = properties.getProperty("rabbitmq.password", ConnectionFactory.DEFAULT_PASS);

    Integer rabbitPort = ConnectionFactory.DEFAULT_AMQP_PORT;

    try {/*from w  w  w .  j a v  a2 s .  co  m*/
        rabbitPort = Integer.parseInt(rabbitPortStr);
    } catch (NumberFormatException ignored) {
        logger.warn("Configuration supplied rabbit port '{}' is not numerical, using default value {}",
                rabbitPortStr, rabbitPort);
    }

    logger.info(
            "Creating new RabbitMQ Service using: \n" + "  host: {}:{}\n" + "  user: {}:{}\n"
                    + "  exchange: {}\n" + "  queue: {}",
            rabbitMQHost, rabbitPort, rabbitUser, rabbitPassword, rabbitMQExchange, rabbitMQQueue);
    try {
        rabbitReceiver = new RabbitService(rabbitMQHost, rabbitPort, rabbitUser, rabbitPassword,
                rabbitMQExchange, rabbitMQQueue, entityManagerFactory);
    } catch (IOException | TimeoutException e) {
        logger.error("Cannot create RabbitMQ service: " + e.getMessage(), e);
        System.exit(1);
    } catch (JAXBException e) {
        logger.error("Cannot create JAXB unmarshaller for messages: " + e.getMessage(), e);
        System.exit(1);
    }

    logger.info("Creating new report scheduler");
    reportScheduler = new ReportScheduler(entityManagerFactory, properties);
    scheduleFrequency = Integer
            .parseInt(properties.getProperty("report.schedule.frequency", SCHEDULE_FREQUENCY.toString()));

    logger.info("Creating new executor with thread pool size {}", THREAD_POOL_SIZE);
    executor = Executors.newScheduledThreadPool(THREAD_POOL_SIZE);
}

From source file:org.debux.webmotion.jpa.Transactional.java

/**
 * Create the transaction and the GenericDAO if the entity name is not 
 * empty or null./*from  w  w w .  j  a va  2 s  .  c  om*/
 * 
 * @param request set EntityManager, EntityTransaction and GenericDAO into the request
 * @param persistenceUnitName precise the persistence unit
 * @param packageEntityName precise the package of entity
 * @param entityName precise the class name of the entity
 * 
 * @throws Exception catch execption to rollback the transaction
 */
public void tx(HttpServletRequest request, String persistenceUnitName, Properties properties,
        String packageEntityName, String entityName) throws Exception {

    // Create factory
    if (persistenceUnitName == null || persistenceUnitName.isEmpty()) {
        persistenceUnitName = DEFAULT_PERSISTENCE_UNIT_NAME;
    }
    EntityManagerFactory factory = factories.get(persistenceUnitName);
    if (factory == null) {
        Configuration subset = properties.subset(persistenceUnitName);
        java.util.Properties additionalProperties = ConfigurationConverter.getProperties(subset);

        factory = Persistence.createEntityManagerFactory(persistenceUnitName, additionalProperties);
        factories.put(persistenceUnitName, factory);
    }

    // Create manager
    EntityManager manager = (EntityManager) request.getAttribute(CURRENT_ENTITY_MANAGER);
    if (manager == null) {
        manager = factory.createEntityManager();
        request.setAttribute(CURRENT_ENTITY_MANAGER, manager);
    }

    // Create generic DAO each time if callback an action on an other entity
    if (entityName != null) {
        String fullEntityName = null;
        if (packageEntityName != null && !packageEntityName.isEmpty()) {
            fullEntityName = packageEntityName + "." + entityName;
        } else {
            fullEntityName = entityName;
        }

        GenericDAO genericDAO = new GenericDAO(manager, fullEntityName);
        request.setAttribute(CURRENT_GENERIC_DAO, genericDAO);

    } else {
        request.setAttribute(CURRENT_GENERIC_DAO, null);
    }

    // Create transaction
    EntityTransaction transaction = (EntityTransaction) request.getAttribute(CURRENT_ENTITY_TRANSACTION);
    if (transaction == null) {
        transaction = manager.getTransaction();
        request.setAttribute(CURRENT_ENTITY_TRANSACTION, transaction);

        transaction.begin();

        try {
            doProcess();
        } catch (Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw e;
        }

        if (transaction.isActive()) {
            transaction.commit();
        }
        manager.close();

    } else {
        doProcess();
    }
}

From source file:de.zib.gndms.dspace.service.test.DSpaceServiceTest.java

@BeforeClass(dependsOnGroups = { "dspaceActionTests" }, dependsOnMethods = { "init" })
private void initContext() {
    context = new ClassPathXmlApplicationContext("classpath:META-INF/00_system.xml");

    final Properties map = new Properties();
    map.put("openjpa.Id", getDbName());
    map.put("openjpa.ConnectionURL", "jdbc:derby:" + getDbPath() + ";create=true");
    //map.put( "openjpa.ConnectionURL", "jdbc:derby:" + getDbPath() );

    final EntityManagerFactory emf = Persistence.createEntityManagerFactory(getDbName(), map);
    setEntityManagerFactory(emf);/*from   ww w  . ja va  2s.com*/
}

From source file:org.apache.falcon.service.FalconJPAService.java

@Override
public void init() throws FalconException {
    Properties props = getPropsforStore();
    entityManagerFactory = Persistence.createEntityManagerFactory(persistenceUnit, props);
    EntityManager entityManager = getEntityManager();
    entityManager.find(EntityBean.class, 1);
    entityManager.find(InstanceBean.class, 1);
    LOG.info("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) entityManagerFactory;
    // Mask the password with '***'
    String logMsg = spi.getConfiguration().getConnectionProperties().replaceAll("Password=.*?,",
            "Password=***,");
    LOG.info("JPA configuration: {0}", logMsg);
    entityManager.getTransaction().commit();
    entityManager.close();/*from  w  w w  .  j a v  a2s  .  c  o  m*/
}

From source file:com.enioka.jqm.tools.Helpers.java

private static EntityManagerFactory createFactory() {
    InputStream fis = null;//from www  .  j  a  va 2  s  .c  o m
    try {
        Properties p = new Properties();
        fis = Helpers.class.getClassLoader().getResourceAsStream("jqm.properties");
        if (fis != null) {
            jqmlogger.trace("A jqm.properties file was found");
            p.load(fis);
            IOUtils.closeQuietly(fis);
            props.putAll(p);
        }
        return Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, props);
    } catch (IOException e) {
        jqmlogger.fatal("conf/jqm.properties file is invalid", e);
        IOUtils.closeQuietly(fis);
        throw new JqmInitError("Invalid JQM configuration file", e);
    } catch (Exception e) {
        jqmlogger.fatal("Unable to connect with the database. Maybe your configuration file is wrong. "
                + "Please check the password or the url in the $JQM_DIR/conf/resources.xml", e);
        throw new JqmInitError("Database connection issue", e);
    } finally {
        IOUtils.closeQuietly(fis);
    }
}

From source file:com.wingnest.blueprints.impls.jpa.internal.wrappers.EntityManagerFactoryWrapper.java

public EntityManagerFactoryWrapper(String persistanceUnitName, @SuppressWarnings("rawtypes") Map props) {
    super();//  ww  w  . j  a  v a  2s  . c o  m
    String pPersistanceUnitName = persistanceUnitName != null ? persistanceUnitName
            : System.getProperty("jpagraph.unit-name");
    if (pPersistanceUnitName == null) {
        ClassLoader cl = this.getClass().getClassLoader();
        try {
            cl.loadClass("com.objectdb.jpa.EMF");
            pPersistanceUnitName = "ObjectDbUnit";
        } catch (ClassNotFoundException e) {
        }
        try {
            cl.loadClass("org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl");
            pPersistanceUnitName = "EclipseLinkUnit";
        } catch (ClassNotFoundException e) {
        }
        try {
            cl.loadClass("org.hibernate.jpa.internal.EntityManagerFactoryImpl");
            pPersistanceUnitName = "HibernateUnit";
        } catch (ClassNotFoundException e) {
        }
    }

    if (pPersistanceUnitName == null)
        throw BpJpaExceptionFactory.cannotBeNull("pPersistanceUnitName");
    if (pPersistanceUnitName.length() == 0)
        throw BpJpaExceptionFactory.cannotBeEmpty("pPersistanceUnitName");

    logger.debug(String.format("persistanceUnitName = %s", pPersistanceUnitName));
    try {
        this.entityManagerFactory = Persistence.createEntityManagerFactory(pPersistanceUnitName, props);
        logger.debug("EntityManagerFactory class : " + entityManagerFactory.getClass().getName());
        this.damper = DamperFactory.create(this.entityManagerFactory);
    } catch (RuntimeException e) {
        logger.error(String.format("Called Persistence.createEntityManagerFactory: persistanceUnitName = '%s'",
                pPersistanceUnitName), e);
        throw e;
    }
}

From source file:com.srotya.tau.api.dao.TestRulesManager.java

@BeforeClass
public static void beforeClass() throws Exception {
    java.util.logging.Logger.getLogger("org.hibernate").setLevel(Level.OFF);
    Properties config = new Properties(System.getProperties());
    File db = new File(TARGET_RULES_DB);
    if (db.exists()) {
        FileUtils.deleteDirectory(db);/*from   w ww.ja  v  a 2 s  .  c o  m*/
    }
    config.setProperty("javax.persistence.jdbc.url", CONNECTION_STRING);
    try {
        emf = Persistence.createEntityManagerFactory("tau", config);
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }

    EntityManager em = emf.createEntityManager();

    RuleGroup ruleGroup = new RuleGroup();
    ruleGroup.setRuleGroupId(RULE_GROUP_ID_1);
    ruleGroup.setRuleGroupName(TEST_RULE_GROUP);
    RuleGroupManager.getInstance().createRuleGroup(em, ruleGroup);

    ruleGroup = new RuleGroup();
    ruleGroup.setRuleGroupId(RULE_GROUP_ID_2);
    ruleGroup.setRuleGroupName(TEST_RULE_GROUP);
    RuleGroupManager.getInstance().createRuleGroup(em, ruleGroup);

    ruleGroup = new RuleGroup();
    ruleGroup.setRuleGroupId(RULE_GROUP_ID_3);
    ruleGroup.setRuleGroupName(TEST_RULE_GROUP);
    RuleGroupManager.getInstance().createRuleGroup(em, ruleGroup);

    ruleGroup = new RuleGroup();
    ruleGroup.setRuleGroupId(RULE_GROUP_ID_5);
    ruleGroup.setRuleGroupName(TEST_RULE_GROUP);
    RuleGroupManager.getInstance().createRuleGroup(em, ruleGroup);

    em.close();
}