List of usage examples for javax.persistence EntityManager persist
public void persist(Object entity);
From source file:org.sigmah.server.endpoint.export.sigmah.handler.OrgUnitModelHandler.java
/** * Save the category element of a question choice element. * //from w ww . java2 s. c om * @param categoryElement * the category element to save. * @param em * the entity manager. */ private void saveOrgUnitModelCategoryElement(CategoryElement categoryElement, EntityManager em) { 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); saveOrgUnitModelCategoryElement(element, em); } 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); } } }
From source file:org.opencastproject.scheduler.impl.persistence.SchedulerServiceDatabaseImpl.java
@Override public void storeEvents(DublinCoreCatalog... events) throws SchedulerServiceDatabaseException { EntityManager em = null; EntityTransaction tx = null;// w w w . j a va2 s. co m try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); for (DublinCoreCatalog event : events) { Long eventId = Long.parseLong(event.getFirst(DublinCore.PROPERTY_IDENTIFIER)); String dcXML; try { dcXML = serializeDublinCore(event); } catch (Exception e1) { logger.error("Could not serialize Dublin Core: {}", e1); throw new SchedulerServiceDatabaseException(e1); } EventEntity entity = new EventEntity(); entity.setEventId(eventId); entity.setEventDublinCore(dcXML); em.persist(entity); } tx.commit(); } catch (SchedulerServiceDatabaseException e) { throw e; } catch (Exception e) { if (tx.isActive()) { tx.rollback(); } logger.error("Could not store events: {}", e); throw new SchedulerServiceDatabaseException(e); } finally { if (em != null) em.close(); } }
From source file:org.apache.juddi.v3.auth.LdapSimpleAuthenticator.java
public String authenticate(String authorizedName, String cred) throws AuthenticationException, FatalErrorException { if (authorizedName == null || "".equals(authorizedName)) { throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName)); }/*from w ww . ja va2 s.c o m*/ int MaxBindingsPerService = -1; int MaxServicesPerBusiness = -1; int MaxTmodels = -1; int MaxBusinesses = -1; try { MaxBindingsPerService = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BINDINGS_PER_SERVICE, -1); MaxServicesPerBusiness = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_SERVICES_PER_BUSINESS, -1); MaxTmodels = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_TMODELS_PER_PUBLISHER, -1); MaxBusinesses = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BUSINESSES_PER_PUBLISHER, -1); } catch (Exception ex) { MaxBindingsPerService = -1; MaxServicesPerBusiness = -1; MaxTmodels = -1; MaxBusinesses = -1; logger.error("config exception! " + authorizedName, ex); } boolean isLdapUser = false; try { env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, AppConfig.getConfiguration() .getString(Property.JUDDI_AUTHENTICATOR_INITIAL_CONTEXT, "com.sun.jndi.ldap.LdapCtxFactory")); env.put(Context.SECURITY_AUTHENTICATION, AppConfig.getConfiguration().getString(Property.JUDDI_AUTHENTICATOR_STYLE, "simple")); env.put(Context.PROVIDER_URL, url); // organization ldap url, example ldap://localhost:389 env.put(Context.SECURITY_PRINCIPAL, authorizedName); env.put(Context.SECURITY_CREDENTIALS, cred); ctx = new InitialLdapContext(env, null); isLdapUser = true; logger.info(authorizedName + " is authenticated"); } catch (ConfigurationException e) { logger.error(authorizedName + " is not authenticated", e); throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName)); } catch (NamingException e) { logger.error(authorizedName + " is not authenticated"); throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName)); } finally { try { ctx.close(); } catch (NamingException e) { logger.error("Context close failure " + e); } } if (isLdapUser) { EntityManager em = PersistenceManager.getEntityManager(); EntityTransaction tx = em.getTransaction(); try { tx.begin(); Publisher publisher = em.find(Publisher.class, authorizedName); if (publisher == null) { logger.warn("Publisher was not found, adding the publisher in on the fly."); publisher = new Publisher(); publisher.setAuthorizedName(authorizedName); publisher.setIsAdmin("false"); publisher.setIsEnabled("true"); publisher.setMaxBindingsPerService(MaxBindingsPerService); publisher.setMaxBusinesses(MaxBusinesses); publisher.setMaxServicesPerBusiness(MaxServicesPerBusiness); publisher.setMaxTmodels(MaxTmodels); publisher.setPublisherName("Unknown"); em.persist(publisher); tx.commit(); } } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } } else { throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName)); } return authorizedName; }
From source file:org.apache.juddi.v3.auth.LdapExpandedAuthenticator.java
public String authenticate(String authorizedName, String cred) throws AuthenticationException, FatalErrorException { if (authorizedName == null || "".equals(authorizedName)) { throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName)); }/*from w w w. j a v a 2 s . c om*/ boolean isLdapUser = false; int MaxBindingsPerService = -1; int MaxServicesPerBusiness = -1; int MaxTmodels = -1; int MaxBusinesses = -1; try { MaxBindingsPerService = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BINDINGS_PER_SERVICE, -1); MaxServicesPerBusiness = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_SERVICES_PER_BUSINESS, -1); MaxTmodels = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_TMODELS_PER_PUBLISHER, -1); MaxBusinesses = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BUSINESSES_PER_PUBLISHER, -1); } catch (Exception ex) { MaxBindingsPerService = -1; MaxServicesPerBusiness = -1; MaxTmodels = -1; MaxBusinesses = -1; logger.error("config exception! " + authorizedName, ex); } try { env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, AppConfig.getConfiguration() .getString(Property.JUDDI_AUTHENTICATOR_INITIAL_CONTEXT, "com.sun.jndi.ldap.LdapCtxFactory")); env.put(Context.SECURITY_AUTHENTICATION, AppConfig.getConfiguration().getString(Property.JUDDI_AUTHENTICATOR_STYLE, "simple")); env.put(Context.PROVIDER_URL, url); // organization ldap url, example ldap://localhost:389 String format = String.format( AppConfig.getConfiguration().getString(Property.JUDDI_AUTHENTICATOR_LDAP_EXPANDED_STR), authorizedName); env.put(Context.SECURITY_PRINCIPAL, format); env.put(Context.SECURITY_CREDENTIALS, cred); ctx = new InitialLdapContext(env, null); isLdapUser = true; logger.info(authorizedName + " is authenticated"); } catch (ConfigurationException e) { logger.error(authorizedName + " is not authenticated", e); throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName)); } catch (NamingException e) { logger.error(authorizedName + " is not authenticated"); throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName)); } finally { try { ctx.close(); } catch (NamingException e) { logger.error("Context close failure " + e); } } if (isLdapUser) { EntityManager em = PersistenceManager.getEntityManager(); EntityTransaction tx = em.getTransaction(); try { tx.begin(); Publisher publisher = em.find(Publisher.class, authorizedName); if (publisher == null) { logger.warn("Publisher was not found, adding the publisher in on the fly."); publisher = new Publisher(); publisher.setAuthorizedName(authorizedName); publisher.setIsAdmin("false"); publisher.setIsEnabled("true"); publisher.setMaxBindingsPerService(MaxBindingsPerService); publisher.setMaxBusinesses(MaxBusinesses); publisher.setMaxServicesPerBusiness(MaxServicesPerBusiness); publisher.setMaxTmodels(MaxTmodels); publisher.setPublisherName("Unknown"); em.persist(publisher); tx.commit(); } } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } } else { throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName)); } return authorizedName; }
From source file:br.edimarmanica.fazenda.control.LoadBBControl.java
private boolean load(Pessoa pessoa, String file) { EntityManager em = Conexao.getEntityManager(); em.getTransaction().begin();/*from w w w . ja v a2s . c om*/ boolean error = false; try (CSVParser parser = CSVParser.parse(new File(file), Charset.forName("ISO-8859-1"), CSVFormat.EXCEL.withHeader())) { for (CSVRecord record : parser) { TipoCaixa tc = new TipoCaixa(); tc.setCdBb(new BigInteger(record.get("Nmero do documento"))); if (tc.getCdBb() != null) { List<TipoCaixa> tcs = daoTipo.search(tc); if (tcs != null && tcs.size() == 1) { Caixa caixa = new Caixa(); caixa.setCdTipoCaixa(tcs.get(0)); caixa.setCdPessoa(pessoa); caixa.setVlCaixa((new BigDecimal(record.get("Valor"))).abs()); caixa.setDtPagamento(new Date(record.get("Data"))); caixa.setDtVencimento(new Date(record.get("Data"))); caixa.setDsCaixa("IMPORTAO BB 02"); em.persist(caixa); } } } } catch (IOException ex) { Logger.getLogger(LoadBBControl.class.getName()).log(Level.SEVERE, null, ex); error = true; } if (!error) { em.getTransaction().commit(); } else { em.getTransaction().rollback(); } em.close(); return !error; }
From source file:org.apache.oozie.service.JPAService.java
/** * Execute multiple update/insert queries in one transaction * @param insertBeans list of beans to be inserted * @param updateQueryList list of update queries * @param deleteBeans list of beans to be deleted * @param em Entity Manager/* w w w . j a v a 2 s.c o m*/ * @throws JPAExecutorException */ public void executeBatchInsertUpdateDelete(Collection<JsonBean> insertBeans, List<QueryEntry> updateQueryList, Collection<JsonBean> deleteBeans, EntityManager em) throws JPAExecutorException { Instrumentation.Cron cron = new Instrumentation.Cron(); try { LOG.trace("Executing Queries in Batch"); cron.start(); em.getTransaction().begin(); if (updateQueryList != null && updateQueryList.size() > 0) { for (QueryEntry q : updateQueryList) { if (instr != null) { instr.incr(INSTRUMENTATION_GROUP_JPA, q.getQueryName().name(), 1); } q.getQuery().executeUpdate(); } } if (insertBeans != null && insertBeans.size() > 0) { for (JsonBean bean : insertBeans) { em.persist(bean); } } if (deleteBeans != null && deleteBeans.size() > 0) { for (JsonBean bean : deleteBeans) { em.remove(em.merge(bean)); } } if (em.getTransaction().isActive()) { if (FaultInjection.isActive("org.apache.oozie.command.SkipCommitFaultInjection")) { throw new RuntimeException("Skipping Commit for Failover Testing"); } em.getTransaction().commit(); } } catch (PersistenceException e) { throw new JPAExecutorException(ErrorCode.E0603, e); } finally { processFinally(em, cron, "batchqueryexecutor", true); } }
From source file:op.care.prescription.DlgOnDemand.java
private void saveSituation(String text) { if (text.isEmpty()) { return;//from w w w . j a va 2 s. c o m } EntityManager em = OPDE.createEM(); Query query = em.createQuery("SELECT s FROM Situations s WHERE s.text = :text"); query.setParameter("text", text); if (query.getResultList().isEmpty()) { Situations neueSituation = new Situations(text); em.persist(neueSituation); cmbSit.setModel(new DefaultComboBoxModel(new Situations[] { neueSituation })); } else { cmbSit.setModel(new DefaultComboBoxModel(query.getResultList().toArray())); } em.close(); }
From source file:com.enioka.jqm.tools.JqmEngine.java
private void purgeDeadJobInstances(EntityManager em, Node node) { em.getTransaction().begin();/* w w w .j a va2 s . co m*/ for (JobInstance ji : em .createQuery("SELECT ji FROM JobInstance ji WHERE ji.node = :node", JobInstance.class) .setParameter("node", node).getResultList()) { History h = em.find(History.class, ji.getId()); if (h == null) { h = Helpers.createHistory(ji, em, State.CRASHED, Calendar.getInstance()); Message m = new Message(); m.setJi(ji.getId()); m.setTextMessage( "Job was supposed to be running at server startup - usually means it was killed along a server by an admin or a crash"); em.persist(m); } em.createQuery("DELETE FROM JobInstance WHERE id = :i").setParameter("i", ji.getId()).executeUpdate(); } em.getTransaction().commit(); }
From source file:cn.buk.hotel.dao.HotelDaoImpl.java
@Override @Transactional/*from ww w . j av a 2s .c o m*/ public int createHotelInfo(HotelInfo hotelInfo) { int retCode = 0; EntityManager em = getEm(); try { List<HotelInfo> hotelInfos = em.createQuery("select o from HotelInfo o where o.hotelCode = :hotelCode") .setParameter("hotelCode", hotelInfo.getHotelCode()).getResultList(); if (hotelInfos.size() > 0) { retCode = 2; } else { em.persist(hotelInfo); retCode = 1; } } catch (Exception ex) { retCode = -1; logger.info("HotelCode: " + hotelInfo.getHotelCode() + ", HotelName: " + hotelInfo.getHotelName() + ": " + ex.getMessage()); } return retCode; }
From source file:info.san.books.app.model.listener.LivreListener.java
@EventHandler public void handle(LivreCreatedEvent e) { EntityManager em = Persistence.getInstance().createEntityManager(); EntityTransaction t = em.getTransaction(); t.begin();/*from w w w .j a va 2 s . co m*/ LivreEntry entry = new LivreEntry(); entry.setEditeur(e.getEditeur()); entry.setFormat(e.getFormat()); entry.setImagePath(e.getImagePath()); entry.setIsbn(e.getIsbn()); entry.setLangue(e.getLangue()); entry.setNbPage(e.getNbPage()); entry.setResume(e.getResume()); entry.setTitre(e.getTitre()); entry.setTitreOriginal(e.getTitreOriginal()); entry.setLu(e.isLu()); entry.setPossede(e.isPossede()); try { entry.setImageAsBase64(this.getImageAsBase64(e.getImagePath())); } catch (IOException ioe) { LivreListener.LOGGER.warn("Cannot save the thumbnail in database: ", ioe); entry.setImageAsBase64(null); } if (e.getSagaId() != null && !e.getSagaId().trim().isEmpty()) { SagaEntry saga = em.getReference(SagaEntry.class, e.getSagaId()); entry.setSaga(saga); } em.persist(entry); t.commit(); }