Example usage for javax.persistence EntityManagerFactory close

List of usage examples for javax.persistence EntityManagerFactory close

Introduction

In this page you can find the example usage for javax.persistence EntityManagerFactory close.

Prototype

public void close();

Source Link

Document

Close the factory, releasing any resources that it holds.

Usage

From source file:org.batoo.jpa.benchmark.BenchmarkTest.java

/**
 * Main test entry point//from   ww  w .j  av a  2 s. c  o m
 * 
 * @since $version
 */
@Test
public void testJpa() {
    Thread.currentThread().setContextClassLoader(
            new TestClassLoader(BenchmarkTest.DB, Thread.currentThread().getContextClassLoader()));

    BenchmarkTest.LOG.info("Benchmark will be run for {0}@{1}",
            BenchmarkTest.TYPE.name().toLowerCase(Locale.ENGLISH), BenchmarkTest.DB);

    BenchmarkTest.LOG.info("Deploying the persistence unit...");

    final EntityManagerFactory emf = Persistence
            .createEntityManagerFactory(BenchmarkTest.TYPE.name().toLowerCase());

    BenchmarkTest.LOG.info("Done deploying the persistence unit.");

    BenchmarkTest.LOG.info("Deploying the persistence unit...");

    final EntityManager em = this.open(emf);
    this.country = new Country();

    this.country.setName("Turkey");
    em.persist(this.country);

    this.close(em);

    this.threadIds = new long[BenchmarkTest.THREAD_COUNT];
    this.currentThreadTimes = new long[BenchmarkTest.THREAD_COUNT];

    BenchmarkTest.LOG.info("Done preparing the countries");

    BenchmarkTest.LOG.info("Running the warm up phase with {0} threads, {1} iterations...",
            BenchmarkTest.THREAD_COUNT, BenchmarkTest.ITERATIONS / 10);
    LinkedBlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>();
    ThreadPoolExecutor pool = this.createExecutor(workQueue);

    // warm mup
    this.test(emf, workQueue, BenchmarkTest.ITERATIONS / 10);
    this.waitUntilFinish(pool);

    BenchmarkTest.LOG.info("Done running warm up phase");

    BenchmarkTest.LOG.info("Starting the benchmark with {0} threads, {1} iterations...",
            BenchmarkTest.THREAD_COUNT, BenchmarkTest.ITERATIONS);

    workQueue = new LinkedBlockingQueue<Runnable>();
    pool = this.createExecutor(workQueue);

    final long started = System.currentTimeMillis();
    // for real
    this.test(emf, workQueue, BenchmarkTest.ITERATIONS);
    this.running = true;
    this.waitUntilFinish(pool);
    this.running = false;
    this.totalTime = (System.currentTimeMillis() - started);

    BenchmarkTest.LOG.info("Benchmark has been completed...");

    try {
        Thread.sleep(1000);
    } catch (final InterruptedException e) {
    }

    emf.close();
}

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;
    EntityManager em = null;/*w w  w .ja v a  2 s .c  o m*/
    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();
        }
    }

}

From source file:org.eclipse.jubula.client.core.persistence.Persistor.java

/**
 * Migrates the structure of the database to match the version of the
 * currently running client. <em>This effectively deletes all Jubula data 
 * currently in the database, so be careful how you use it.</em>
 * // www. ja  v  a  2  s  .c o m
 * @throws JBFatalException
 *             if a fatal exception occurs during migration.
 * @throws JBException
 *             if a general exception occurs during migration.
 * @return true if migration succeeded; false otherwise
 */
public static boolean migrateDatabaseStructure() throws JBFatalException, JBException {
    boolean migrationSuccess = false;
    EntityManagerFactory migrationEntityManagerFactory = null;

    try {
        migrationEntityManagerFactory = createEntityManagerFactory(dbConnectionInfo, user, pw, dburl);
        migrationSuccess = installDbScheme(migrationEntityManagerFactory);
        instance = instance(user, pw, dburl, new NullProgressMonitor());
        instance.m_newDbSchemeInstalled = true;
    } finally {
        if (migrationEntityManagerFactory != null) {
            migrationEntityManagerFactory.close();
        }
    }
    return migrationSuccess;
}

From source file:org.ejbca.extra.caservice.ExtRACAServiceWorker.java

private void init() {

    // Read configuration properties
    // First we get it from the built in configuration in the properties file using ConfigurationHolder
    // Second we try to override this value with a value from the properties of this specific worker, configured in the GUI
    // Oh, and if no configuration exist it uses the hard coded values from the top of this file.

    String persistenceUnit = this.properties.getProperty("externalra-caservice.persistenceunit",
            "RAMessage1DS");
    log.debug("externalra-caservice.hibernateresource: " + persistenceUnit);

    String keystorePath = this.properties.getProperty("externalra-caservice.keystore.path",
            "keystore/extrakeystore.p12");
    log.debug("externalra-caservice.keystore.path: " + keystorePath);

    keystorePwd = this.properties.getProperty("externalra-caservice.keystore.pwd", "foo123");
    log.debug("externalra-caservice.keystore.pwd: " + keystorePwd);

    encryptionRequired = Boolean/*from   w ww  .j  ava  2s .  c om*/
            .valueOf(this.properties.getProperty("externalra-caservice.encryption.required", "false"));
    log.debug("externalra-caservice.encryption.required: " + encryptionRequired);

    signatureRequired = Boolean
            .valueOf(this.properties.getProperty("externalra-caservice.signature.required", "false"));
    log.debug("externalra-caservice.signature.required: " + signatureRequired);

    caname = this.properties.getProperty("externalra-caservice.raissuer", "AdminCA1");
    log.debug("externalra-caservice.raissuer: " + caname);

    whiteList = this.properties.getProperty("externalra-caservice.whitelist", "");
    log.debug("externalra-caservice.whitelist: " + whiteList);

    // Initialize the JPA provider with the current persistence unit
    if (entityManagerFactories.get(persistenceUnit) == null) {
        EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory(persistenceUnit);
        EntityManagerFactory entityManagerFactoryOld = entityManagerFactories.putIfAbsent(persistenceUnit,
                entityManagerFactory);
        if (entityManagerFactoryOld != null && !entityManagerFactoryOld.equals(entityManagerFactory)) {
            entityManagerFactory.close();
        } else {
            log.info("Created new entity manager factory for persistence unit '" + persistenceUnit + "'");
        }
    }
    msgHome = new MessageHome(entityManagerFactories.get(persistenceUnit), MessageHome.MESSAGETYPE_EXTRA, true); // We manage transactions ourself for this DataSource

    try {
        serviceKeyStore = new RAKeyStore(keystorePath, keystorePwd);
    } catch (Exception e) {
        if (encryptionRequired || signatureRequired) {
            log.error("Error reading ExtRACAService keystore", e);
        } else {
            log.debug("ExtRACAService KeyStore couldn't be configured, but isn't required");
        }
    }
}

From source file:org.jbpm.bpmn2.IntermediateEventTest.java

@Test
@RequirePersistence//from ww  w  .  jav  a  2  s . c  om
public void testEventTypesLifeCycle() throws Exception {
    // JBPM-4246
    KieBase kbase = createKnowledgeBase("BPMN2-IntermediateCatchSignalBetweenUserTasks.bpmn2");
    EntityManagerFactory separateEmf = Persistence.createEntityManagerFactory("org.jbpm.persistence.jpa");
    Environment env = createEnvironment(separateEmf);
    ksession = createKnowledgeSession(kbase, null, env);
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task", new DoNothingWorkItemHandler());
    ksession.startProcess("BPMN2-IntermediateCatchSignalBetweenUserTasks");

    int signalListSize = ksession.execute(new ExecutableCommand<Integer>() {
        public Integer execute(Context context) {
            SingleSessionCommandService commandService = (SingleSessionCommandService) ((CommandBasedStatefulKnowledgeSession) ksession)
                    .getRunner();
            InternalKnowledgeRuntime kruntime = (InternalKnowledgeRuntime) commandService.getKieSession();
            ProcessPersistenceContextManager contextManager = (ProcessPersistenceContextManager) kruntime
                    .getEnvironment().get(EnvironmentName.PERSISTENCE_CONTEXT_MANAGER);
            ProcessPersistenceContext pcontext = contextManager.getProcessPersistenceContext();

            List<Long> processInstancesToSignalList = pcontext.getProcessInstancesWaitingForEvent("MySignal");
            return processInstancesToSignalList.size();
        }
    });

    // Process instance is not waiting for signal
    assertThat(signalListSize).isEqualTo(0);

    ksession.getWorkItemManager().completeWorkItem(1, null);

    signalListSize = ksession.execute(new ExecutableCommand<Integer>() {
        public Integer execute(Context context) {
            SingleSessionCommandService commandService = (SingleSessionCommandService) ((CommandBasedStatefulKnowledgeSession) ksession)
                    .getRunner();
            InternalKnowledgeRuntime kruntime = (InternalKnowledgeRuntime) commandService.getKieSession();
            ProcessPersistenceContextManager contextManager = (ProcessPersistenceContextManager) kruntime
                    .getEnvironment().get(EnvironmentName.PERSISTENCE_CONTEXT_MANAGER);
            ProcessPersistenceContext pcontext = contextManager.getProcessPersistenceContext();

            List<Long> processInstancesToSignalList = pcontext.getProcessInstancesWaitingForEvent("MySignal");
            return processInstancesToSignalList.size();
        }
    });

    // Process instance is waiting for signal now
    assertThat(signalListSize).isEqualTo(1);

    ksession.signalEvent("MySignal", null);

    signalListSize = ksession.execute(new ExecutableCommand<Integer>() {
        public Integer execute(Context context) {
            SingleSessionCommandService commandService = (SingleSessionCommandService) ((CommandBasedStatefulKnowledgeSession) ksession)
                    .getRunner();
            InternalKnowledgeRuntime kruntime = (InternalKnowledgeRuntime) commandService.getKieSession();
            ProcessPersistenceContextManager contextManager = (ProcessPersistenceContextManager) kruntime
                    .getEnvironment().get(EnvironmentName.PERSISTENCE_CONTEXT_MANAGER);
            ProcessPersistenceContext pcontext = contextManager.getProcessPersistenceContext();

            List<Long> processInstancesToSignalList = pcontext.getProcessInstancesWaitingForEvent("MySignal");
            return processInstancesToSignalList.size();
        }
    });

    // Process instance is not waiting for signal
    assertThat(signalListSize).isEqualTo(0);

    ksession.getWorkItemManager().completeWorkItem(2, null);

    ksession.dispose();
    ksession = null;
    separateEmf.close();
}

From source file:org.kie.server.services.jbpm.JbpmKieServerExtension.java

@Override
public void destroy(KieServerImpl kieServer, KieServerRegistry registry) {
    ((AbstractDeploymentService) deploymentService).shutdown();

    if (executorService != null) {
        executorService.destroy();//from  w w w  . j a  va 2  s .  co  m
    }

    EntityManagerFactory emf = EntityManagerFactoryManager.get().remove(persistenceUnitName);
    if (emf != null && emf.isOpen()) {
        emf.close();
    }
}

From source file:org.opencms.db.jpa.CmsSqlManager.java

/**
 * Close all instances of EntityManagerFactory.
 *///from w w  w. j a v  a  2 s.  c  om
public static synchronized void destroy() {

    if (CmsLog.INIT.isDebugEnabled()) {
        trackOn();
    }

    try {
        m_openCmsEmPool.close();
    } catch (Exception e) {
        // do nothing
    }
    if (m_factoryTable != null) {
        Set<String> s = m_factoryTable.keySet();
        EntityManagerFactory emf;
        for (String f : s) {
            emf = m_factoryTable.get(f);
            if (emf != null) {
                emf.close();
                m_factoryTable.remove(f);
            }
        }
    }
    m_isInitialized = false;
}

From source file:org.openejb.persistence.OpenJpaProviderTest.java

public void testOpenJpaProvider() throws Exception {
    System.setProperty(javax.naming.Context.URL_PKG_PREFIXES, "org.openejb.persistence");

    PersistenceDeployer deployer = new PersistenceDeployer(new TestDataSourceResolver());

    Map<String, EntityManagerFactory> map = deployer.deploy(Thread.currentThread().getContextClassLoader());

    EntityManagerFactory emf = map.get("openjpa-test-unit");
    assertNotNull("EntityManagerFactory", emf);

    EntityManager em = emf.createEntityManager();
    assertNotNull("EntityManager", em);

    em.getTransaction().begin();//  www  . j av  a  2 s  .c o  m
    em.persist(new AllFieldTypes());
    em.getTransaction().commit();
    em.close();

    em = emf.createEntityManager();
    em.getTransaction().begin();
    em.createQuery("delete from AllFieldTypes").executeUpdate();
    em.getTransaction().commit();
    em.close();
    emf.close();
}

From source file:org.rhq.server.metrics.migrator.DataMigratorRunner.java

/**
 * Closes an existing entity manager factory
 *
 * @param entityManagerFactory/*from   w w w  .j  a v  a  2 s .c om*/
 */
private void closeEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
    if (entityManagerFactory != null) {
        entityManagerFactory.close();
    }
}

From source file:org.rhq.server.metrics.migrator.DataSourceTest.java

public static void main(String[] args) throws Exception {
    BasicConfigurator.configure();//from w  ww .java  2 s  .c  o  m
    Logger.getRootLogger().setLevel(Level.INFO);
    Logger.getLogger("org.rhq").setLevel(Level.DEBUG);
    EntityManagerFactory entityManagerFactory = null;
    EntityManager entityManager = null;
    ExistingDataBulkExportSource source = null;
    try {
        entityManagerFactory = createEntityManager();
        entityManager = entityManagerFactory.createEntityManager();
        source = new ExistingPostgresDataBulkExportSource(entityManager,
                "SELECT  schedule_id, time_stamp, value, minvalue, maxvalue FROM RHQ_MEASUREMENT_DATA_NUM_1D");
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        source.initialize();
        int rowIndex = 0;
        int maxResults = 30000;
        for (;;) {
            List<Object[]> existingData = source.getData(rowIndex, maxResults);
            if (existingData.size() < maxResults) {
                break;
            } else {
                rowIndex += maxResults;
            }
        }
        stopWatch.stop();
        System.out.println("Execution: " + stopWatch);
    } finally {
        if (source != null) {
            source.close();
        }
        if (entityManager != null) {
            entityManager.close();
        }
        if (entityManagerFactory != null) {
            entityManagerFactory.close();
        }
    }
}