Example usage for javax.persistence EntityManager getTransaction

List of usage examples for javax.persistence EntityManager getTransaction

Introduction

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

Prototype

public EntityTransaction getTransaction();

Source Link

Document

Return the resource-level EntityTransaction object.

Usage

From source file:com.epam.training.taranovski.web.project.repository.implementation.OfferBidRepositoryImplementation.java

@Override
public List<Employee> getOffersForVacancy(Vacancy vacancy) {
    EntityManager em = entityManagerFactory.createEntityManager();
    List<Employee> list = new LinkedList<>();
    try {//from   w  ww.j  a v a 2s. c o m
        em.getTransaction().begin();

        TypedQuery<Employee> query = em.createNamedQuery("OfferBid.findEmployeeOffersForVacancy",
                Employee.class);
        query.setParameter("vacancy", vacancy);
        list = query.getResultList();

        em.getTransaction().commit();
    } catch (RuntimeException e) {
        Logger.getLogger(OfferBidRepositoryImplementation.class.getName()).info(e);
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        em.close();
    }

    return list;
}

From source file:com.doculibre.constellio.wicket.panels.admin.thesaurus.AddEditThesaurusPanel.java

@Override
protected void onSave(AjaxRequestTarget target) {
    if (importCompleted) {
        RecordCollectionServices collectionServices = ConstellioSpringUtils.getRecordCollectionServices();
        SkosServices skosServices = ConstellioSpringUtils.getSkosServices();
        Thesaurus importedThesaurus = thesaurusModel.getObject();

        AdminCollectionPanel collectionAdminPanel = (AdminCollectionPanel) findParent(
                AdminCollectionPanel.class);
        RecordCollection collection = collectionAdminPanel.getCollection();
        Thesaurus initialThesaurus = collection.getThesaurus();

        EntityManager entityManager = ConstellioPersistenceContext.getCurrentEntityManager();
        if (!entityManager.getTransaction().isActive()) {
            entityManager.getTransaction().begin();
        }/*ww  w.j  a  v a  2s  . c o m*/
        //            collectionServices.makePersistent(collection, false);
        if (initialThesaurus != null) {
            //                Set<SkosConcept> deletedConcepts = skosServices.merge(initialThesaurus, importedThesaurus);
            //                for (SkosConcept deletedConcept : deletedConcepts) {
            //                    skosServices.makeTransient(deletedConcept);
            //                }
            //                skosServices.makePersistent(initialThesaurus);
            skosServices.makeTransient(initialThesaurus);

            importedThesaurus.setRecordCollection(collection);
            collection.setThesaurus(importedThesaurus);
            skosServices.makePersistent(importedThesaurus);
        } else {
            importedThesaurus.setRecordCollection(collection);
            collection.setThesaurus(importedThesaurus);
            skosServices.makePersistent(importedThesaurus);
        }
        //            skosServices.makePersistent(importedThesaurus);
        entityManager.getTransaction().commit();
    }
}

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;
        }/*  w w w . jav a2s. c  o 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: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 www.j a v  a 2 s  .  c o m*/
    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:com.epam.training.taranovski.web.project.repository.implementation.OfferBidRepositoryImplementation.java

@Override
public boolean delete(OfferBid something) {
    EntityManager em = entityManagerFactory.createEntityManager();
    boolean success = true;
    OfferBid managedManagedOfferBid = null;
    try {/*  w w  w  . ja  v a 2 s . c  om*/
        em.getTransaction().begin();
        managedManagedOfferBid = em.merge(something);
        em.remove(managedManagedOfferBid);
        em.getTransaction().commit();

        success = true;
    } catch (RuntimeException e) {
        Logger.getLogger(OfferBidRepositoryImplementation.class.getName()).info(e);
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
            success = false;
        }
        em.close();
    }

    return success;
}

From source file:pl.com.bottega.testutils.HibernateExtendedJpaDialect.java

/**
 * This method is overridden to set custom isolation levels on the connection
 * @param entityManager/*from w w w  .ja v  a2 s .  c  o m*/
 * @param definition
 * @return
 * @throws PersistenceException
 * @throws SQLException
 * @throws TransactionException
 */
@Override
public Object beginTransaction(final EntityManager entityManager, final TransactionDefinition definition)
        throws PersistenceException, SQLException, TransactionException {
    Session session = (Session) entityManager.getDelegate();
    if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) {
        getSession(entityManager).getTransaction().setTimeout(definition.getTimeout());
    }

    entityManager.getTransaction().begin();
    logger.debug("Transaction started");

    session.doWork(new Work() {

        public void execute(Connection connection) throws SQLException {
            logger.debug("The connection instance is {}", connection);
            logger.debug(
                    "The isolation level of the connection is {} and the isolation level set on the transaction is {}",
                    connection.getTransactionIsolation(), definition.getIsolationLevel());
            DataSourceUtils.prepareConnectionForTransaction(connection, definition);
        }
    });

    return prepareTransaction(entityManager, definition.isReadOnly(), definition.getName());
}

From source file:com.jada.admin.AdminLookupDispatchAction.java

protected void commitAndRestartTransaction() throws Exception {
    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();
    em.getTransaction().commit();
    em = JpaConnection.getInstance().getCurrentEntityManager();
    em.getTransaction().begin();/*from  w ww .  j ava  2s . c o m*/
}

From source file:eu.trentorise.smartcampus.permissionprovider.oauth.IsolationSupportHibernateJpaDialect.java

@Override
public Object beginTransaction(EntityManager entityManager, TransactionDefinition definition)
        throws PersistenceException, SQLException, TransactionException {

    boolean readOnly = definition.isReadOnly();
    Connection connection = this.getJdbcConnection(entityManager, readOnly).getConnection();
    connectionThreadLocal.set(connection);
    originalIsolation.set(DataSourceUtils.prepareConnectionForTransaction(connection, definition));

    entityManager.getTransaction().begin();

    return prepareTransaction(entityManager, readOnly, definition.getName());
}

From source file:in.bookmylab.jpa.JpaDAO.java

public void saveProfile(UserProfile profile) {
    EntityManager em = emf.createEntityManager();
    try {/*  w  w w.  j a  v  a2s  .c  om*/
        em.getTransaction().begin();
        if (profile.profileId == null) {
            em.persist(profile);
        } else {
            em.merge(profile);
        }
        em.getTransaction().commit();
    } finally {
        em.close();
    }
}

From source file:streaming.test.StreamingTest.java

public void creationSerie() {
    Serie serie = new Serie("Dexter", "Synopsis");

    for (Long i = 1L; i <= 8L; i++) {
        Saison saison = new Saison(i, 2005L + i);
        serie.getSaison().add(saison);//w ww  . j av  a 2 s.c  om
        saison.setSerie(serie);
        for (Long j = 1L; j <= i; j++) {
            Episode episode = new Episode(j, "E" + j);
            saison.getEpisode().add(episode);
            episode.setSaison(saison);
            for (Long k = 1L; k <= i; k++) {
                Lien lien = new Lien("URL" + k);
                episode.getLiens().add(lien);
                lien.setEpisode(episode);
            }
        }
    }
    EntityManager em = Persistence.createEntityManagerFactory("StreamingPU").createEntityManager();
    em.getTransaction().begin();
    em.persist(serie);
    em.getTransaction().commit();

}