Example usage for javax.persistence EntityManager merge

List of usage examples for javax.persistence EntityManager merge

Introduction

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

Prototype

public <T> T merge(T entity);

Source Link

Document

Merge the state of the given entity into the current persistence context.

Usage

From source file:portal.api.impl.PortalJpaController.java

public MANOprovider updateMANOprovider(MANOprovider c) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();/*from  w  w w .j  a va  2  s . c  o m*/
    MANOprovider resis = entityManager.merge(c);
    entityTransaction.commit();

    return resis;
}

From source file:portal.api.impl.PortalJpaController.java

public Infrastructure updateInfrastructure(Infrastructure c) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();//  w  ww .j  av  a 2s. c om
    Infrastructure resis = entityManager.merge(c);
    entityTransaction.commit();

    return resis;
}

From source file:portal.api.impl.PortalJpaController.java

public VxFOnBoardedDescriptor updateVxFOnBoardedDescriptor(VxFOnBoardedDescriptor c) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();//from  w w w  .  java 2 s  .c  o m
    VxFOnBoardedDescriptor resis = entityManager.merge(c);
    entityTransaction.commit();

    return resis;
}

From source file:portal.api.impl.PortalJpaController.java

public ExperimentOnBoardDescriptor updateExperimentOnBoardDescriptor(ExperimentOnBoardDescriptor c) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();//from w ww .  ja v a 2 s .co m
    ExperimentOnBoardDescriptor resis = entityManager.merge(c);
    entityTransaction.commit();

    return resis;
}

From source file:com.thejustdo.servlet.CargaMasivaServlet.java

/**
 * Builds an object with the owner that at future will be the owner of all
 * the dream boxes created under the broad approach of massive load.
 *
 * @param args Set of properties for the buyer as follows: <ul> <li> 0:
 * Social reason. </li> <li> 1: NIT number. </li> <li> 2: Name. </li> <li>
 * 3: Phone. </li> <li> 4: Email. </li> </ul>
 * @return The built object ready to be persisted and linked.
 *//*from   w  w w  .ja va 2 s . co m*/
private Buyer buildGeneralBuyer(EntityManager em, String... args) {
    // 0. Parsing parameters.
    long idNumber = Long.parseLong(args[1]);
    String buyer_name = args[0];
    String buyer_last_name = args[2];
    String buyer_email = args[4];
    String buyer_cellphone = args[3];

    // 1. If the buyer already exist, we update the info.
    log.info(String.format("Working on buyer with NIT: %d", idNumber));
    Buyer buyer = BuyerQueries.findBuyerById(idNumber, em);
    buyer = (buyer == null) ? new Buyer(idNumber) : buyer;
    buyer.setGivenNames(buyer_name);
    buyer.setLastName(buyer_last_name);
    buyer.setSecondLastName("N/A");
    buyer.setDocumentType("NIT");
    buyer.setPaymentMethod("Cargo a cuenta");
    buyer.setEmail(buyer_email);
    buyer.setCellPhone(buyer_cellphone);
    buyer.setStatus(true);
    em.merge(buyer);
    return buyer;
}

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 .ja  va 2 s.  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:org.opencastproject.search.impl.persistence.SearchServiceDatabaseImpl.java

private void populateSeriesData() throws SearchServiceDatabaseException {
    EntityManager em = null;
    EntityTransaction tx = null;//from w w  w  .j  a v a 2  s  .  com
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        TypedQuery<SearchEntity> q = (TypedQuery<SearchEntity>) em.createNamedQuery("Search.getNoSeries");
        List<SearchEntity> seriesList = q.getResultList();
        for (SearchEntity series : seriesList) {
            String mpSeriesId = MediaPackageParser.getFromXml(series.getMediaPackageXML()).getSeries();
            if (StringUtils.isNotBlank(mpSeriesId) && !mpSeriesId.equals(series.getSeriesId())) {
                logger.info("Fixing missing series ID for episode {}, series is {}", series.getMediaPackageId(),
                        mpSeriesId);
                series.setSeriesId(mpSeriesId);
                em.merge(series);
            }
        }
        tx.commit();
    } catch (Exception e) {
        logger.error("Could not update media package: {}", e.getMessage());
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new SearchServiceDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.wso2.carbon.humantask.core.store.HumanTaskStore.java

public void updateDeploymentUnitDao(final DeploymentUnitDAO deploymentUnit) throws Exception {
    HumanTaskServiceComponent.getHumanTaskServer().getTaskEngine().getScheduler()
            .execTransaction(new Callable<DeploymentUnitDAO>() {
                public DeploymentUnitDAO call() throws Exception {
                    EntityManager entityManager = engine.getDaoConnectionFactory().getConnection()
                            .getEntityManager();
                    entityManager.merge(deploymentUnit);
                    return deploymentUnit;
                }/*from   w  ww . j  a va 2 s.  c  o  m*/
            });
}

From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java

/**
 * saves or update a newsdrilldown.//from w w w . ja v  a 2s.c o m
 *
 * @param news the newsdrilldown to save
 * @param em   the em
 * @return the saved newsdrilldown, the new db id will be set
 * @throws Exception the exception
 */
private News saveNews(News news, EntityManager em) throws Exception {

    News n = getNews(news.getFs_id(), news.getLanguage());
    // newsdrilldown with FirstSpirit-ID exists

    if (n != null) {
        // update newsdrilldown

        n.setFs_id(news.getFs_id());
        n.setContent(news.getContent());
        n.setDate(news.getDate());
        n.setHeadline(news.getHeadline());
        n.setSubheadline(news.getSubheadline());
        n.setTeaser(news.getTeaser());
        n.setLanguage(news.getLanguage());
        n.setUrl(news.getUrl());
        n.setVersion(1);
        n.setLastmodified(news.getLastmodified());

        n.setCategories(news.getCategories());

        news = em.merge(n);
    } else {
        // save new newsdrilldown
        em.persist(news);
    }

    return news;

}

From source file:op.care.supervisor.PnlHandover.java

private java.util.List<Component> addCommands() {
    java.util.List<Component> list = new ArrayList<Component>();

    /***/*from  w  w  w .jav a 2s  . co m*/
     *      _   _
     *     | \ | | _____      __
     *     |  \| |/ _ \ \ /\ / /
     *     | |\  |  __/\ V  V /
     *     |_| \_|\___| \_/\_/
     *
     */
    if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.INSERT, internalClassID)) {
        JideButton addButton = GUITools.createHyperlinkButton(
                SYSTools.xx("nursingrecords.handover.tooltips.btnadd"), SYSConst.icon22add,
                new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {
                        new DlgHOReport(new Handovers((Homes) cmbHomes.getSelectedItem()), new Closure() {
                            @Override
                            public void execute(Object report) {
                                if (report != null) {
                                    EntityManager em = OPDE.createEM();
                                    try {
                                        em.getTransaction().begin();
                                        final Handovers myHO = em.merge((Handovers) report);
                                        myHO.getUsersAcknowledged().add(
                                                em.merge(new Handover2User(myHO, OPDE.getLogin().getUser())));
                                        em.getTransaction().commit();

                                        LocalDate day = new LocalDate(myHO.getPit());

                                        final String key = DateFormat.getDateInstance().format(myHO.getPit());

                                        createCP4Day(day);
                                        expandDay(day);

                                        buildPanel();
                                        GUITools.scroll2show(jspHandover, cpMap.get(key), cpsHandover,
                                                new Closure() {
                                                    @Override
                                                    public void execute(Object o) {
                                                        //                                            GUITools.flashBackground(linemapHO.get(myHO), Color.YELLOW, 2);
                                                    }
                                                });
                                    } catch (OptimisticLockException ole) {
                                        OPDE.warn(ole);
                                        if (em.getTransaction().isActive()) {
                                            em.getTransaction().rollback();
                                        }
                                        if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                            OPDE.getMainframe().emptyFrame();
                                            OPDE.getMainframe().afterLogin();
                                        }
                                        OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                                    } catch (Exception e) {
                                        if (em.getTransaction().isActive()) {
                                            em.getTransaction().rollback();
                                        }
                                        OPDE.fatal(e);
                                    } finally {
                                        em.close();
                                    }
                                }
                            }
                        });
                    }
                });
        list.add(addButton);
    }

    final JideButton btnControllingToday = GUITools.createHyperlinkButton(
            SYSTools.xx("nursingrecords.handover.tooltips.btnControllingToday"), SYSConst.icon22magnify1, null);
    btnControllingToday.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            btnControllingToday.setEnabled(false);
            HandoversTools.printSupervision(new LocalDate(), (Homes) cmbHomes.getSelectedItem(), new Closure() {
                @Override
                public void execute(Object o) {
                    btnControllingToday.setEnabled(true);
                }
            });
        }
    });
    list.add(btnControllingToday);

    final JideButton btnControllingYesterday = GUITools.createHyperlinkButton(
            SYSTools.xx("nursingrecords.handover.tooltips.btnControllingYesterday"), SYSConst.icon22magnify1,
            null);
    btnControllingYesterday.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            btnControllingYesterday.setEnabled(false);
            HandoversTools.printSupervision(new LocalDate().minusDays(1), (Homes) cmbHomes.getSelectedItem(),
                    new Closure() {
                        @Override
                        public void execute(Object o) {
                            btnControllingYesterday.setEnabled(true);
                        }
                    });
        }
    });
    list.add(btnControllingYesterday);

    return list;
}