Example usage for javax.persistence EntityManager refresh

List of usage examples for javax.persistence EntityManager refresh

Introduction

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

Prototype

public void refresh(Object entity);

Source Link

Document

Refresh the state of the instance from the database, overwriting changes made to the entity, if any.

Usage

From source file:org.eclipse.jubula.client.ui.rcp.editors.CentralTestDataEditor.java

/**
 * Does the refresh cascading manually//  www.  jav a2 s .  com
 * @param session
 *            the session in which you want to refresh 
 * @param testDataCategory
 *            the category which child's should be refreshed
 */
private void refreshChilds(final EntityManager session, IPersistentObject testDataCategory) {
    for (ITestDataCategoryPO catergory : ((ITestDataCategoryPO) testDataCategory).getCategoryChildren()) {
        session.refresh(catergory);
        refreshChilds(session, catergory);
    }
    for (ITestDataCubePO dataCube : ((ITestDataCategoryPO) testDataCategory).getTestDataChildren()) {
        session.refresh(dataCube);
        ITDManager manager = dataCube.getDataManager();
        session.refresh(manager);
    }
}

From source file:org.eclipse.jubula.client.ui.rcp.editors.CentralTestDataEditor.java

/** {@inheritDoc} */
public void doSave(IProgressMonitor monitor) {
    monitor.beginTask(Messages.EditorsSaveEditors, IProgressMonitor.UNKNOWN);
    EditSupport editSupport = getEditorHelper().getEditSupport();
    try {/*from   www  .j av a  2s  . c om*/
        editSupport.saveWorkVersion();
        final EntityManager masterSession = GeneralStorage.getInstance().getMasterSession();
        IPersistentObject original = editSupport.getOriginal();
        if (original != null) {
            masterSession.refresh(original);
            if (original instanceof ITestDataCategoryPO) {
                refreshChilds(masterSession, original);
            }
        }
        updateReferencedParamNodes();

        getEditorHelper().resetEditableState();
        getEditorHelper().setDirty(false);
    } catch (IncompatibleTypeException pmce) {
        handlePMCompNameException(pmce);
    } catch (PMException e) {
        PMExceptionHandler.handlePMExceptionForMasterSession(e);
        try {
            reOpenEditor(((PersistableEditorInput) getEditorInput()).getNode());
        } catch (PMException e1) {
            PMExceptionHandler.handlePMExceptionForEditor(e, this);
        }
    } catch (ProjectDeletedException e) {
        PMExceptionHandler.handleProjectDeletedException();
    } finally {
        monitor.done();
    }

}

From source file:org.giwi.finistjug.camel.demo.processor.ListOfSessionsProcessor.java

@SuppressWarnings("unchecked")
@Override//from   ww w  . j av  a2 s . c  o  m
public void process(final Exchange exchange) throws Exception {
    final List<JUGSession> listOfSessions = new ArrayList<JUGSession>();
    exchange.getIn().setBody(null);

    // Rcupration de l'entityManager
    final EntityManager em = EntityManagerUtil.getEntityManager();
    final ExpressionBuilder builder = new ExpressionBuilder();
    final ReadAllQuery databaseQuery = new ReadAllQuery(Jugpresentation.class, builder);
    final Query query = ((JpaEntityManager) em.getDelegate()).createQuery(databaseQuery);
    // excution de la requte
    try {
        final List<Jugpresentation> jugPres = query.getResultList();
        final DozerBeanMapper mapper = exchange.getContext().getRegistry().lookup("mapper",
                DozerBeanMapper.class);
        for (final Jugpresentation jugP : jugPres) {
            em.refresh(jugP);
            // mapping Dozer
            listOfSessions.add(mapper.map(jugP, JUGSession.class));
        }
    } catch (final NoResultException e) {
        // pas de rsultat trouv, c'est pas bien grave
        if (LOG.isInfoEnabled()) {
            LOG.info(e);
        }
    }
    final ListeDesSessionsResponse resp = new ListeDesSessionsResponse();
    resp.setListeDesSessions(listOfSessions);
    exchange.getIn().setBody(resp);
}

From source file:server.Folder.java

@Override
public Indexable reload() {
    EntityManager em = HibernateSession.getLocalEntityManager();
    em.refresh(this);
    return this;
}

From source file:mil.navy.med.dzreg.dao.RegistriesManagerDAO.java

/**
 * Returns the registry profile of a person.
 * @param personId  unique identifier of person
 * @return  PersonRegistryProfileType/*www  . j a  v a  2 s  .c  om*/
 */
public PersonRegistryProfileType getRegistryProfile(Long personId) {
    EntityManager em = null;
    PersonRegistryProfileType profile = null;
    PersistentServiceFactory psf = null;

    if (personId != null) {
        try {
            psf = PersistentServiceFactory.getInstance(REGISTRY_MANAGER_PU);
            em = psf.getEntityManager();

            Query query = em.createNamedQuery("DzPatients.findByPatid");
            query.setParameter("patid", personId);
            DzPatients result = (DzPatients) query.getSingleResult();

            if (result != null) {
                em.refresh(result);
                //log.debug(result.toString());
                try {
                    profile = map(result);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (javax.persistence.NoResultException nr) {
            log.error("No data found for personId=" + personId);
        } finally {
            em.close();
        }
    } else {
        log.error("personId can not be null or empty");
    }

    return profile;
}

From source file:org.meveo.service.billing.impl.InvoiceService.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void createAgregatesAndInvoice(BillingAccount billingAccount, Long billingRunId, User currentUser)
        throws BusinessException, Exception {
    log.debug("createAgregatesAndInvoice tx status={}", txReg.getTransactionStatus());
    EntityManager em = getEntityManager();
    BillingRun billingRun = em.find(BillingRun.class, billingRunId);
    em.refresh(billingRun);
    try {/*from  www . ja  v a2 s . c  o m*/
        billingAccount = em.find(billingAccount.getClass(), billingAccount.getId());
        em.refresh(billingAccount);
        currentUser = em.find(currentUser.getClass(), currentUser.getId());
        em.refresh(currentUser);

        Long startDate = System.currentTimeMillis();
        BillingCycle billingCycle = billingRun.getBillingCycle();
        if (billingCycle == null) {
            billingCycle = billingAccount.getBillingCycle();
        }
        if (billingCycle == null) {
            throw new BusinessException("Cant find the billing cycle");
        }
        InvoiceType invoiceType = billingCycle.getInvoiceType();
        if (invoiceType == null) {
            invoiceType = invoiceTypeService.getDefaultCommertial(currentUser);
        }
        Invoice invoice = new Invoice();
        invoice.setInvoiceType(invoiceType);
        invoice.setBillingAccount(billingAccount);
        invoice.setBillingRun(billingRun);
        invoice.setAuditable(billingRun.getAuditable());
        invoice.setProvider(billingRun.getProvider());
        // ticket 680
        Date invoiceDate = billingRun.getInvoiceDate();
        invoice.setInvoiceDate(invoiceDate);

        Integer delay = billingCycle.getDueDateDelay();
        Date dueDate = invoiceDate;
        if (delay != null) {
            dueDate = DateUtils.addDaysToDate(invoiceDate, delay);
        }
        invoice.setDueDate(dueDate);

        PaymentMethodEnum paymentMethod = billingAccount.getPaymentMethod();
        if (paymentMethod == null) {
            paymentMethod = billingAccount.getCustomerAccount().getPaymentMethod();
        }
        invoice.setPaymentMethod(paymentMethod);
        invoice.setProvider(billingRun.getProvider());

        em.persist(invoice);

        // create(invoice, currentUser, currentUser.getProvider());
        log.debug("created invoice entity with id={},  tx status={}, em open={}", invoice.getId(),
                txReg.getTransactionStatus(), em.isOpen());
        ratedTransactionService.createInvoiceAndAgregates(billingAccount, invoice,
                billingRun.getLastTransactionDate(), currentUser);
        log.debug("created aggregates tx status={}, em open={}", txReg.getTransactionStatus(), em.isOpen());
        em.joinTransaction();

        if (billingRun.getProvider().isDisplayFreeTransacInInvoice()) {
            em.createNamedQuery("RatedTransaction.updateInvoicedDisplayFree")
                    .setParameter("billingAccount", billingAccount)
                    .setParameter("lastTransactionDate", billingRun.getLastTransactionDate())
                    .setParameter("billingRun", billingRun).setParameter("invoice", invoice).executeUpdate();
        } else {
            em.createNamedQuery("RatedTransaction.updateInvoiced")
                    .setParameter("billingAccount", billingAccount)
                    .setParameter("lastTransactionDate", billingRun.getLastTransactionDate())
                    .setParameter("billingRun", billingRun).setParameter("invoice", invoice).executeUpdate();

        }

        StringBuffer num1 = new StringBuffer("000000000");
        num1.append(invoice.getId() + "");
        String invoiceNumber = num1.substring(num1.length() - 9);
        int key = 0;

        for (int i = 0; i < invoiceNumber.length(); i++) {
            key = key + Integer.parseInt(invoiceNumber.substring(i, i + 1));
        }

        invoice.setTemporaryInvoiceNumber(invoiceNumber + "-" + key % 10);
        // getEntityManager().merge(invoice);
        Long endDate = System.currentTimeMillis();

        log.info("createAgregatesAndInvoice BR_ID=" + billingRun.getId() + ", BA_ID=" + billingAccount.getId()
                + ", Time en ms=" + (endDate - startDate));
    } catch (Exception e) {
        log.error("Error for BA=" + billingAccount.getCode() + " : ", e);

        RejectedBillingAccount rejectedBA = new RejectedBillingAccount(billingAccount, billingRun,
                e.getMessage());
        rejectedBillingAccountService.create(rejectedBA, currentUser);
    }
}

From source file:sf.net.experimaestro.scheduler.Job.java

/**
 * Called when the job has ended// ww  w . j  a  v a2s.  c o  m
 *
 * @param eoj The message
 * @param em  The entity manager
 * @param t   The transaction
 */
private void endOfJobMessage(EndOfJobMessage eoj, EntityManager em, Transaction t) {
    this.endTimestamp = eoj.timestamp;

    // Lock all the required dependencies and refresh

    LOGGER.info("Job %s has ended with code %d", this, eoj.code);

    // (1) Release required resources
    LOGGER.debug("Release dependencies of job [%s]", this);
    try {
        final Collection<Dependency> requiredResources = getDependencies();
        for (Dependency dependency : requiredResources) {
            try {
                dependency.from.lock(t, true);
                em.refresh(dependency.from);
                em.refresh(dependency);
                dependency.unlock(em);

            } catch (Throwable e) {
                LOGGER.error(e, "Error while unlocking dependency %s", dependency);
            }
        }
    } catch (RuntimeException e) {
        LOGGER.error(e, "Error while unactivating dependencies");
    }

    // (2) dispose old XPM process

    try {
        if (process != null) {
            LOGGER.debug("Disposing of old XPM process [%s]", process);
            process.dispose();
            process = null;
        } else {
            LOGGER.warn("There was no XPM process attached...");
        }
    } catch (Exception e) {
        LOGGER.error("Could not dispose of the old process checker %s", e);
    }

    // (3) Change state (DONE or ERROR depending on the end of job status code)
    setState(eoj.code == 0 ? ResourceState.DONE : ResourceState.ERROR);
}

From source file:br.unicamp.cotuca.dpd.pd12.acinet.vagalmail.servlet.Configuracoes.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF-8");

    if (request.getRequestURI().contains("/pasta")) {
        String acao = request.getParameter("acao"), url = request.getParameter("url"),
                novo = request.getParameter("novo");

        JSONObject obj = new JSONObject();
        if (acao == null || url == null) {
            obj.put("erro", "Solicitao invlida");
            obj.writeJSONString(response.getWriter());
            return;
        }/*  ww  w . jav a  2s.co  m*/

        if ((acao.equals("renomear") || acao.equals("nova")) && novo == null) {
            obj.put("erro", "Solicitao invlida");
            obj.writeJSONString(response.getWriter());
            return;
        }

        try {
            Conta conta = (Conta) request.getSession().getAttribute("conta");
            Store store = Logar.getImapStore(conta);

            Folder pasta = null;

            if (!acao.equals("nova")) {
                URLName urln = new URLName(url);
                pasta = store.getFolder(urln);

                if (pasta.isOpen())
                    pasta.close(false);
            }

            switch (acao) {
            case "renomear":
                if (pasta.renameTo(store.getFolder(novo))) {
                    obj.put("sucesso", "Renomeado com sucesso");
                } else {
                    obj.put("erro", "Erro ao renomear a pasta");
                }
                break;
            case "esvaziar":
                pasta.open(Folder.READ_WRITE);
                pasta.setFlags(1, pasta.getMessageCount(), new Flags(Flags.Flag.DELETED), true);
                pasta.expunge();
                obj.put("sucesso", "Esvaziado com sucesso");
                break;
            case "excluir":
                if (pasta.delete(true)) {
                    obj.put("sucesso", "Excludo com sucesso");
                } else {
                    obj.put("erro", "Erro ao excluir a pasta");
                }
                break;
            case "nova":
                pasta = store.getFolder(novo);
                if (!pasta.exists()) {
                    if (pasta.create(Folder.HOLDS_FOLDERS | Folder.HOLDS_MESSAGES)) {
                        obj.put("sucesso", "Criado com sucesso");
                    } else {
                        obj.put("erro", "Erro ao criar a pasta");
                    }
                } else {
                    obj.put("erro", "Erro ao criar a pasta");
                }
                break;
            }
        } catch (MessagingException ex) {
            obj.put("erro", "Erro ao processar solicitao");
        }

        obj.writeJSONString(response.getWriter());

        return;
    }

    String metodo = request.getParameter("acao");
    if (metodo == null) {
        return;
    } else if (metodo.equals("nova")) {
        EntityManager em = BD.getEntityManager();

        try {
            em.getTransaction().begin();

            Login usuario = Logar.getLogin(request.getSession());

            Conta conta = new Conta();
            conta.setEmail(request.getParameter("email"));
            conta.setImapHost(request.getParameter("imapHost"));
            conta.setImapPort(Integer.parseInt(request.getParameter("imapPort")));
            conta.setImapPassword(request.getParameter("imapPassword"));
            conta.setImapUser(request.getParameter("imapLogin"));
            conta.setSmtpHost(request.getParameter("smtpHost"));
            conta.setSmtpPort(Integer.parseInt(request.getParameter("smtpPort")));
            conta.setSmtpPassword(request.getParameter("smtpPassword"));
            conta.setSmtpUser(request.getParameter("smtpLogin"));
            conta.setIdLogin(usuario);

            em.persist(conta);
            em.merge(usuario);

            em.getTransaction().commit();
            em.refresh(conta);
            em.refresh(usuario);

            request.setAttribute("mensagem", "sucesso");
        } catch (Logar.NaoAutenticadoException | PersistenceException ex) {
            em.getTransaction().rollback();

            request.setAttribute("mensagem", "erro");
        }

        request.getRequestDispatcher("/conf.jsp?metodo=nova").forward(request, response);
    } else if (metodo.equals("conta")) {
        EntityManager em = BD.getEntityManager();

        try {
            em.getTransaction().begin();

            Conta conta = (Conta) request.getSession().getAttribute("conta");

            em.refresh(conta);
            conta.setEmail(request.getParameter("email"));
            conta.setImapHost(request.getParameter("imapHost"));
            conta.setImapPort(Integer.parseInt(request.getParameter("imapPort")));
            conta.setImapPassword(request.getParameter("imapPassword"));
            conta.setImapUser(request.getParameter("imapLogin"));
            conta.setSmtpHost(request.getParameter("smtpHost"));
            conta.setSmtpPort(Integer.parseInt(request.getParameter("smtpPort")));
            conta.setSmtpPassword(request.getParameter("smtpPassword"));
            conta.setSmtpUser(request.getParameter("smtpLogin"));

            em.getTransaction().commit();

            request.setAttribute("mensagem", "sucesso");
        } catch (PersistenceException ex) {
            em.getTransaction().rollback();

            request.setAttribute("mensagem", "erro");
        }

        request.getRequestDispatcher("/conf.jsp?metodo=conta").forward(request, response);

    } else if (metodo.equals("senha")) {
        EntityManager em = BD.getEntityManager();

        try {

            Login usuario = Logar.getLogin(request.getSession());

            em.refresh(usuario);

            String senatu = request.getParameter("senAtu"), novasen = request.getParameter("senNova"),
                    novasen2 = request.getParameter("senNova2");

            if (novasen.equals(novasen2) && senatu.equals(usuario.getSenha())) {

                em.getTransaction().begin();

                usuario.setSenha(novasen);

                em.getTransaction().commit();

                request.setAttribute("mensagem", "sucesso");
            } else {
                if (!novasen.equals(novasen2))
                    request.setAttribute("mensagem", "senneq");
                else
                    request.setAttribute("mensagem", "antsen");
            }
        } catch (Logar.NaoAutenticadoException | PersistenceException ex) {
            em.getTransaction().rollback();

            request.setAttribute("mensagem", "erro");
        }

        request.getRequestDispatcher("/conf.jsp?metodo=senha").forward(request, response);

    }
}

From source file:sf.net.experimaestro.scheduler.Resource.java

public void save(Transaction transaction) {
    final EntityManager em = transaction.em();

    // Lock all the dependencies
    // This avoids to miss any notification
    List<EntityLock> locks = new ArrayList<>();
    lockDependencies: while (true) {
        // We loop until we get all the locks - using a timeout just in case
        for (Dependency dependency : getDependencies()) {
            final EntityLock lock = dependency.from.lock(transaction, false, 100);
            if (lock == null) {
                for (EntityLock _lock : locks) {
                    _lock.close();/*from  w  w  w .j  a  v  a 2  s. com*/
                }
                continue lockDependencies;
            }

            locks.add(lock);
        }

        break;
    }

    for (Dependency dependency : getDependencies()) {
        if (!em.contains(dependency.from)) {
            dependency.from = em.find(Resource.class, dependency.from.getId());
        } else {
            em.refresh(dependency.from);
        }
    }

    prepared = true;
    em.persist(this);

    // Update the status
    updateStatus();
}

From source file:it.webappcommon.lib.jpa.ControllerStandard.java

/**
 * Usato specialmente per aggiornare dopo un salvataggio. Nel caso delle
 * applicazioni web usiamo em che si chiude dopo la request quindi gli
 * oggetti non si aggiornano in automatico dopo il salvataggio.
 * /*from   www.j a v a 2s. com*/
 * @param <T>
 * @param classObj
 * @param id
 * @return
 * @throws Exception
 */
public <T extends EntityBaseStandard> T findAndRefresh(Class<T> classObj, Object id) throws Exception {
    T returnValue = null;

    EntityManagerFactory emf = null;
    EntityManager em = null;
    try {
        emf = getEntityManagerFactory();
        em = emf.createEntityManager();

        returnValue = (T) em.find(classObj, id);

        if (returnValue != null) {
            // if (lazyCloseEM) {
            em.refresh(returnValue);
            // }
        }

    } catch (Exception e) {
        // logger.error("Errore su find di controller : " + e.getMessage() +
        // " " + e.getCause() != null ? e.getCause().getMessage() : "");
        ExceptionLogger.logExceptionWithCause(logger, e);
        throw e;
    } finally {
        if (!passedEm) {
            PersistenceManagerUtil.close(em);
        }
        em = null;
    }
    return returnValue;
}