Example usage for javax.persistence EntityManager isOpen

List of usage examples for javax.persistence EntityManager isOpen

Introduction

In this page you can find the example usage for javax.persistence EntityManager isOpen.

Prototype

public boolean isOpen();

Source Link

Document

Determine whether the entity manager is open.

Usage

From source file:com.thruzero.domain.jpa.transaction.JpaDatabaseTransactionMgr.java

@Override
public void rollbackTransaction() {
    if (isTransactionActive()) {
        EntityManager entityManager = doGetCurrentPersistenceManager(false);

        entityManager.getTransaction().rollback();

        if (entityManager.isOpen()) {
            entityManager.close();//from ww  w  .  j  ava 2 s  .  co  m
        }
    }
}

From source file:com.thruzero.domain.jpa.transaction.JpaDatabaseTransactionMgr.java

protected EntityManager doGetCurrentPersistenceManager(boolean autoCreateTransaction) {
    JpaTransactionState txState = localTransactionState.get();
    EntityManager currentEntityManager = txState.getEntityManager();

    if (autoCreateTransaction && !isTransactionActive()) {
        if (currentEntityManager != null && currentEntityManager.isOpen()) {
            transactionMgrLogHelper.logEntityManagerNotClosedWarning();
            currentEntityManager.close();
        }//from w w w  .j  a v  a2s . c om

        // begins a transaction if not currently active
        currentEntityManager = createEntityManager();
        if (!isTransactionActive()) {
            currentEntityManager.getTransaction().begin();
        }

        txState.setEntityManager(currentEntityManager);
    }

    return currentEntityManager;
}

From source file:com.abiquo.server.core.enterprise.EnterpriseRep.java

public EnterpriseRep(final EntityManager entityManager) {
    assert entityManager != null;
    assert entityManager.isOpen();

    this.entityManager = entityManager;
    this.enterpriseDAO = new EnterpriseDAO(entityManager);
    userDAO = new UserDAO(entityManager);
    roleDAO = new RoleDAO(entityManager);
    ottSessionDAO = new OneTimeTokenSessionDAO(entityManager);
    privilegeDAO = new PrivilegeDAO(entityManager);
    roleLdapDAO = new RoleLdapDAO(entityManager);
}

From source file:de.zib.gndms.GORFX.context.service.globus.resource.TaskResource.java

@Override
public void remove() {

    if (taskAction != null) {
        Log log = taskAction.getLog();/* www . j  av  a  2 s  .  c  o  m*/
        log.debug("Removing task resource: " + getID());
        AbstractTask tsk = taskAction.getModel();
        boolean cleanUp = false;
        if (tsk != null) {
            if (!tsk.isDone()) {
                // task is still running cancel it and cleanup entity manager
                taskAction.setCancelled(true);
                log.debug("cancel task " + tsk.getWid());
                cleanUp = true;
                if (future != null) {
                    future.cancel(true);
                    try {
                        // give cancel some time
                        Thread.sleep(2000L);
                    } catch (InterruptedException e) {
                        logger.debug(e);
                    }
                }

                try {
                    EntityManager em = taskAction.getEntityManager();
                    if (em != null && em.isOpen()) {
                        try {
                            EntityTransaction tx = em.getTransaction();
                            if (tx.isActive())
                                tx.rollback();
                        } finally {
                            em.close();
                        }
                    }
                } catch (Exception e) {
                    // don't bother with exceptions
                    log.debug("Exception on task future cancel: " + e.toString(), e);
                }
            }

            EntityManager em = home.getEntityManagerFactory().createEntityManager();
            TxFrame tx = new TxFrame(em);
            // cleanup if necessary
            try {
                try {
                    Task t = em.find(Task.class, tsk.getId());
                    t.setPostMortem(true);
                    tx.commit();

                    if (cleanUp) {
                        log.debug("Triggering task cleanup");
                        try {
                            taskAction.setOwnEntityManager(em);
                            taskAction.cleanUpOnFail(t);
                        } catch (Exception e) {
                            log.debug("Exception on cleanup: " + e.toString());
                        }
                    }

                    // remove task from db
                    log.debug("Removing task: " + t.getId());
                    tx.begin();
                    em.remove(t);
                    tx.commit();
                } finally {
                    tx.finish();
                    if (em.isOpen())
                        em.close();
                }
            } catch (Exception e) {
                log.debug("Exception on task resource removal: " + e.toString());
                e.printStackTrace();
            }
        }
    }
}

From source file:de.zib.gndms.GORFX.context.service.globus.resource.ExtTaskResourceHome.java

private void resumeTasks() throws Exception {

    logger.debug("Checking for aborted tasks.");
    EntityManager em = null;
    List<String> rs = null;
    try {/*  w  w  w.j  av a  2  s  .c  o m*/
        em = system.getEntityManagerFactory().createEntityManager();
        Query q = em.createNamedQuery("unfinishedTaskIds");
        rs = q.getResultList();
        if (rs.size() == 0) {
            logger.debug("No tasks found :-)");
            return;
        }
    } finally {
        if (em != null && em.isOpen())
            em.close();
    }

    logger.debug("Try to resume " + rs.size() + " tasks");
    for (String id : rs) {
        logger.debug("Resuming " + id);
        Resource k = find(getKeyForId(id));
    }
}

From source file:de.zib.gndms.infra.tests.FileTransferActionTest.java

@BeforeClass(groups = { "net", "db", "sys", "action", "task" })
public void beforeClass() throws ServerException, IOException, ClientException {

    PropertyConfigurator.configure(logFileConfig);
    runDatabase();//from  w  ww  . j a  v a 2 s. c  om
    transferData.initialize();

    // create orq
    FileTransferORQ orq = new FileTransferORQ();
    orq.setSourceURI(transferData.getSourceURI());
    orq.setTargetURI(transferData.getDestinationURI());
    orq.setFileMap(transferData.getFileMap());

    // create orq-calc
    FileTransferORQCalculator calc = new FileTransferORQCalculator();
    calc.setORQArguments(orq);
    // calc.setNetAux( getSys().getNetAux() );

    TransientContract con = calc.createOffer();
    PersistentContract pcon = con.acceptAt(new DateTime());

    // creating offertype
    OfferType ot;
    EntityManager em = null;
    try {
        em = getSys().getEntityManagerFactory().createEntityManager();
        ot = em.find(OfferType.class, "http://gndms.zib.de/ORQTypes/FileTransfer");
        if (ot == null) {
            ot = createFTOfferType();
            em.getTransaction().begin();
            em.persist(ot);
            em.getTransaction().commit();
        }

    } finally {
        if (em != null && em.isOpen())
            em.close();
        ot = createFTOfferType();
    }

    // create task
    task = new Task();
    task.setId(getSys().nextUUID());
    task.setDescription(orq.getDescription());
    task.setTerminationTime(pcon.getCurrentTerminationTime());
    task.setOfferType(ot);
    task.setOrq(orq);
    task.setContract(pcon);
    Calendar tt = pcon.getDeadline();
    tt.add(Calendar.YEAR, 10);
    task.setTerminationTime(tt);
}

From source file:de.zib.gndms.infra.system.GNDMSystemDirectory.java

@SuppressWarnings({ "MethodWithTooExceptionsDeclared", "OverloadedMethodsWithSameNumberOfParameters" })
public TaskAction newTaskAction(final @NotNull EntityManagerFactory emf, final @NotNull String offerTypeKey)
        throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException,
        InvocationTargetException {
    EntityManager em = emf.createEntityManager();
    try {//from   w  w w.ja  v a2s .  com
        return newTaskAction(em, offerTypeKey);
    } finally {
        if (!em.isOpen())
            em.close();
    }
}

From source file:de.zib.gndms.infra.system.GNDMSystemDirectory.java

/**
 * Creates a new EntityManager using <tt>emf</tt>.
 *
 * <p>Calls {@link #loadConfigletStates(javax.persistence.EntityManager)} and
 * {@link #createOrUpdateConfiglets(de.zib.gndms.model.common.ConfigletState[])} to load all configlets managed by
 * this EntityManager and update the {@link #configlets} map.
 * Old Configlets will be removed and shutted down using {@link #shutdownConfiglets()} 
 *
 * @param emf the factory the EntityManager will be created of
 */// w  w  w.j  av a2  s  .  co  m
public synchronized void reloadConfiglets(final EntityManagerFactory emf) {
    ConfigletState[] states;
    EntityManager em = emf.createEntityManager();
    try {
        states = loadConfigletStates(em);
        createOrUpdateConfiglets(states);
        shutdownOldConfiglets(em);
    } finally {
        if (em.isOpen())
            em.close();
    }
}

From source file:de.zib.gndms.infra.tests.FileTransferActionTest.java

@Test(groups = { "net", "db", "sys", "action", "task" })
public void testIt() throws ResourceException, ExecutionException, InterruptedException {

    EntityManager em = null;
    try {/*from  w w  w.  ja v a2 s  .  co m*/
        em = getSys().getEntityManagerFactory().createEntityManager();
        em.getTransaction().begin();
        em.persist(task);
        em.getTransaction().commit();
        FileTransferTaskAction action = new FileTransferTaskAction(em, task);
        Future<AbstractTask> serializableFuture = getSys().submitAction(action, log);
        assert serializableFuture.get().getState().equals(TaskState.FINISHED);
        FileTransferResult ftr = (FileTransferResult) task.getData();
        for (String s : Arrays.asList(ftr.getFiles()))
            System.out.println(s);

    } finally {
        if (em != null && em.isOpen())
            em.close();
    }
}

From source file:com.abiquo.server.core.infrastructure.InfrastructureRep.java

public InfrastructureRep(final EntityManager entityManager) {
    assert entityManager != null;
    assert entityManager.isOpen();

    this.entityManager = entityManager;

    this.dao = new DatacenterDAO(entityManager);
    this.rackDao = new RackDAO(entityManager);
    this.ucsRackDao = new UcsRackDAO(entityManager);
    this.machineDao = new MachineDAO(entityManager);
    this.hypervisorDao = new HypervisorDAO(entityManager);
    this.datastoreDao = new DatastoreDAO(entityManager);
    this.remoteServiceDao = new RemoteServiceDAO(entityManager);
    this.repositoryDao = new RepositoryDAO(entityManager);
    this.networkDao = new NetworkDAO(entityManager);
    this.datacenterLimitDao = new DatacenterLimitsDAO(entityManager);
    this.storageRep = new StorageRep(entityManager);
    this.vlanDao = new VLANNetworkDAO(entityManager);
    this.ipPoolDao = new IpPoolManagementDAO(entityManager);
    this.dhcpOptionDAO = new DhcpOptionDAO(entityManager);
    this.virtualMachineDao = new VirtualMachineDAO(entityManager);
}