List of usage examples for javax.persistence EntityManager persist
public void persist(Object entity);
From source file:portal.api.impl.PortalJpaController.java
public void saveUser(PortalUser bu) { logger.info("Will save PortalUser = " + bu.getName()); EntityManager entityManager = entityManagerFactory.createEntityManager(); EntityTransaction entityTransaction = entityManager.getTransaction(); entityTransaction.begin();/*from ww w.j a v a 2 s .co m*/ entityManager.persist(bu); entityManager.flush(); entityTransaction.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; }//from w ww.ja va2 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:fr.mby.opa.picsimpl.dao.DbProposalDao.java
@Override public ProposalBag createBag(final ProposalBag bag, final long branchId) { Assert.notNull(bag, "No ProposalBag supplied !"); Assert.isNull(bag.getId(), "Id should not be set for creation !"); new TxCallback(this.getEmf()) { @Override/*from w w w . ja v a 2 s . com*/ // @SuppressWarnings("unchecked") protected void executeInTransaction(final EntityManager em) { // Retrieve branch final ProposalBranch branch = em.find(ProposalBranch.class, branchId, LockModeType.PESSIMISTIC_WRITE); if (branch == null) { throw new ProposalBranchNotFoundException(); } // Retrieve base bag (parent bag) and lock the row // final Query findParentQuery = em.createNamedQuery(ProposalBag.FIND_LAST_BRANCH_BAG); // findParentQuery.setParameter("branchId", branchId); // findParentQuery.setLockMode(LockModeType.PESSIMISTIC_WRITE); // Persist bag with its parent // final ProposalBag parentBag = Iterables.getFirst(findParentQuery.getResultList(), null); // bag.setBaseProposal(parentBag); // em.persist(bag); // Persist bag with its parent bag.setBaseProposal(branch.getHead()); em.persist(bag); // Update branch head pointer branch.setHead(bag); em.merge(branch); } }; return bag; }
From source file:org.eclipse.smila.connectivity.deltaindexing.jpa.impl.DeltaIndexingManagerImpl.java
/** * Creates or updates an entry in the delta indexing database and sets the visited flag. * /*from w w w . j ava2 s . co m*/ * @param em * the EntityManager * @param dao * the DeltaIndexingDao if a former entry exists or null * @param id * the id of the record (just for logging) * @param hash * the delta indexing hash * @param isCompound * boolean flag if the record identified by id is a compound record (true) or not (false) * @throws DeltaIndexingException * if any error occurs */ private void visitNewOrChangedDao(final EntityManager em, DeltaIndexingDao dao, final ConnectivityId id, final String hash, final boolean isCompound) throws DeltaIndexingException { final EntityTransaction transaction = em.getTransaction(); try { transaction.begin(); if (dao == null) { dao = new DeltaIndexingDao(id, hash, isCompound, true); em.persist(dao); if (_log.isTraceEnabled()) { _log.trace("created and visited id: " + id); } } else { dao.modifyAndVisit(hash); em.merge(dao); if (_log.isTraceEnabled()) { _log.trace("visited Id:" + id); } } transaction.commit(); } catch (final Exception e) { if (transaction.isActive()) { transaction.rollback(); } throw new DeltaIndexingException("error visiting id: " + id, e); } }
From source file:it.attocchi.jpa2.JpaController.java
public <T extends Serializable> void insert(T o) throws Exception { EntityManager em = getEntityManager(); try {/*from w w w .j av a 2 s .c o m*/ if (!globalTransactionOpen) em.getTransaction().begin(); em.persist(o); if (!globalTransactionOpen) em.getTransaction().commit(); } catch (Exception e) { throw e; } finally { // Close the database connection: if (!globalTransactionOpen) { if (em.getTransaction().isActive()) em.getTransaction().rollback(); closeEm(); // em.close(); } } }
From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.test.NewsITCase.java
/** * Test persistence.// w w w.ja v a 2s . c o m * * @throws Exception the exception */ @Test public void testPersistence() throws Exception { long size = countNews(); EntityManager em = emf.createEntityManager(); EntityTransaction tx = null; try { tx = em.getTransaction(); tx.begin(); News news = new News(); news.setContent("Spider-man was seen."); news.setHeadline("The amazing spider-man"); news.setFs_id(1l); news.setLanguage("DE"); news.setTeaser("spider-man"); NewsCategory sport = new NewsCategory(); sport.setFs_id(2l); sport.setName("Sport"); sport.setLanguage("DE"); NewsMetaCategory soccer = new NewsMetaCategory(); soccer.setFs_id(3l); soccer.setLanguage("DE"); soccer.setName("Fussball"); if (sport.getMetaCategories() == null) { sport.setMetaCategories(new ArrayList<NewsMetaCategory>()); } sport.getMetaCategories().add(soccer); if (news.getCategories() == null) { news.setCategories(new ArrayList<NewsCategory>()); } news.getCategories().add(sport); em.persist(news); em.flush(); tx.commit(); assertEquals("Entity not filled", size + 1, countNews()); Query query = em.createQuery("SELECT mc FROM metaCategory mc WHERE fs_id=3"); NewsMetaCategory metaCat = (NewsMetaCategory) query.getSingleResult(); assertNotNull(metaCat); query = em.createQuery( "SELECT c FROM category c join c.metaCategories mc WHERE mc.fs_id=" + metaCat.getFs_id()); NewsCategory category = (NewsCategory) query.getSingleResult(); assertNotNull(category); query = em.createQuery("SELECT n FROM news n join n.categories c WHERE c.fs_id=" + category.getFs_id()); News n = (News) query.getSingleResult(); assertNotNull(n); } finally { if (tx != null && tx.isActive()) { tx.rollback(); } em.close(); } }
From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java
/** * saves or updates a newscategory./*from w w w . java 2s . c om*/ * * @param metaCategory the category * @param em the em * @return the category with the new id * @throws Exception the exception */ private NewsMetaCategory saveNewsMetaCategory(NewsMetaCategory metaCategory, EntityManager em) throws Exception { // try loading the category for the firstspirit id NewsMetaCategory cat = getNewsMetaCategory(metaCategory.getFs_id(), metaCategory.getLanguage(), em); if (cat != null) { // update existing category cat.setFs_id(metaCategory.getFs_id()); cat.setLanguage(metaCategory.getLanguage()); cat.setName(metaCategory.getName()); cat.setVersion(metaCategory.getVersion()); cat.setLastmodified(metaCategory.getLastmodified()); // update cat = em.merge(cat); return cat; } else { // save to db em.persist(metaCategory); } return metaCategory; }
From source file:it.drwolf.ridire.session.async.Mapper.java
private void lookForNoMoreAvailableResources(Job persistedJob, Set<CrawledResource> childResources, File f, EntityManager entityManager) throws IOException, NotSupportedException, SystemException, SecurityException, IllegalStateException, RollbackException, HeuristicMixedException, HeuristicRollbackException { for (CrawledResource cr : persistedJob.getCrawledResources()) { if (!childResources.contains(cr)) { cr.setNoMoreAvailable(true); entityManager.persist(cr); this.moveResourceInAttic(cr, f); }/*from w ww .j a va 2s .c o m*/ } }
From source file:org.opencastproject.messages.MailService.java
public static MessageSignatureDto mergeMessageSignature(MessageSignature signature, String organization, EntityManager em) { ArrayList<CommentDto> comments = new ArrayList<CommentDto>(); for (Comment c : signature.getComments()) { comments.add(CommentDatabaseUtils.mergeComment(c, em)); }//from w w w . j a v a2 s. co m Option<MessageSignatureDto> signatureOption = findMessageSignature(option(signature.getId()), signature.getName(), organization, em); MessageSignatureDto dto; if (signatureOption.isSome()) { dto = signatureOption.get(); dto.setComments(comments); dto.setCreationDate(signature.getCreationDate()); dto.setCreator(signature.getCreator().getUsername()); dto.setSender(signature.getSender().getAddress()); dto.setSenderName(signature.getSender().getName()); dto.setReplyTo(signature.getReplyTo().map(getAddress).getOrElseNull()); dto.setReplyToName(signature.getReplyTo().map(getName).getOrElseNull()); dto.setName(signature.getName()); dto.setSignature(signature.getSignature()); em.merge(dto); } else { dto = new MessageSignatureDto(signature.getName(), organization, signature.getCreator().getUsername(), signature.getSender().getAddress(), signature.getSender().getName(), signature.getReplyTo().map(getAddress).getOrElseNull(), signature.getReplyTo().map(getName).getOrElseNull(), signature.getSignature(), signature.getCreationDate(), comments); em.persist(dto); } return dto; }
From source file:org.sigmah.server.endpoint.export.sigmah.handler.ProjectModelHandler.java
/** * Save the category element of a question choice element. * /*from w w w .j a v a 2 s .c o m*/ * @param categoryElement * the category element to save. * @param em * the entity manager. */ private void saveProjectModelCategoryElement(CategoryElement categoryElement, EntityManager em, HashMap<Object, Object> modelesReset, HashSet<Object> modelesImport) { if (!modelesImport.contains(categoryElement)) { modelesImport.add(categoryElement); if (!modelesReset.containsKey(categoryElement)) { CategoryElement key = categoryElement; categoryElement.setId(null); CategoryType parentType = categoryElement.getParentType(); if (!modelesImport.contains(parentType)) { modelesImport.add(parentType); if (!modelesReset.containsKey(parentType)) { CategoryType parentKey = parentType; parentType.setId(null); List<CategoryElement> elements = parentType.getElements(); if (elements != null) { parentType.setElements(null); em.persist(parentType); for (CategoryElement element : elements) { categoryElement.setParentType(parentType); saveProjectModelCategoryElement(element, em, modelesReset, modelesImport); } parentType.setElements(elements); em.merge(parentType); } else { em.persist(parentType); } modelesReset.put(parentKey, parentType); } else { parentType = (CategoryType) modelesReset.get(parentType); } } categoryElement.setParentType(parentType); em.persist(categoryElement); modelesReset.put(key, categoryElement); } else { categoryElement = (CategoryElement) modelesReset.get(categoryElement); } } }