List of usage examples for javax.persistence EntityManager persist
public void persist(Object entity);
From source file:org.opencastproject.series.impl.persistence.SeriesServiceDatabaseImpl.java
@Override public DublinCoreCatalog storeSeries(DublinCoreCatalog dc) throws SeriesServiceDatabaseException, UnauthorizedException { if (dc == null) { throw new SeriesServiceDatabaseException("Invalid value for Dublin core catalog: null"); }/* w w w .ja v a 2 s .c o m*/ String seriesId = dc.getFirst(DublinCore.PROPERTY_IDENTIFIER); String seriesXML; try { seriesXML = serializeDublinCore(dc); } catch (Exception e1) { logger.error("Could not serialize Dublin Core: {}", e1); throw new SeriesServiceDatabaseException(e1); } EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); DublinCoreCatalog newSeries = null; try { tx.begin(); SeriesEntity entity = getSeriesEntity(seriesId, em); if (entity == null) { // no series stored, create new entity entity = new SeriesEntity(); entity.setOrganization(securityService.getOrganization().getId()); entity.setSeriesId(seriesId); entity.setSeries(seriesXML); em.persist(entity); newSeries = dc; } else { // Ensure this user is allowed to update this series String accessControlXml = entity.getAccessControl(); if (accessControlXml != null) { AccessControlList acl = AccessControlParser.parseAcl(accessControlXml); User currentUser = securityService.getUser(); Organization currentOrg = securityService.getOrganization(); if (!AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, EDIT_SERIES_PERMISSION)) { throw new UnauthorizedException( currentUser + " is not authorized to update series " + seriesId); } } entity.setSeries(seriesXML); em.merge(entity); } tx.commit(); return newSeries; } catch (Exception e) { logger.error("Could not update series: {}", e.getMessage()); if (tx.isActive()) { tx.rollback(); } throw new SeriesServiceDatabaseException(e); } finally { em.close(); } }
From source file:com.busimu.core.dao.impl.UserMngDaoPolicyJpaImpl.java
private void initExampleData() throws Exception { EntityManager em = emf.createEntityManager(); try {// w w w .j a va 2 s . c o m EntityTransaction tx = em.getTransaction(); tx.begin(); User player1 = new User("student@busimu.com", "ssssss", "s", User.Type.STUDENT); player1.setStatus(User.Status.ACTIVE); User player2 = new User("zhangsan@busimu.com", "123456", "", User.Type.STUDENT); player2.setStatus(User.Status.ACTIVE); User player3 = new User("lisi@busimu.com", "123456", "?", User.Type.STUDENT); player3.setStatus(User.Status.ACTIVE); User teacher = new User("teacher@busimu.com", "tttttt", "t", User.Type.TEACHER); teacher.setStatus(User.Status.ACTIVE); em.persist(player1); em.persist(player2); em.persist(player3); em.persist(teacher); Campaign campaign = teacher.createCampagin("", Campaign.Type.COURSE); SimMarket south = campaign.addMarket("??"); SimMarket central = campaign.addMarket("?"); SimMarket north = campaign.addMarket("?"); SimMarket east = campaign.addMarket("?"); SimMarket west = campaign.addMarket(""); SimCorporation ibm = south.addCorporation("IBM", new Color(128, 128, 255)); SimCorporation ericsson = south.addCorporation("Ericsson", Color.BLUE); SimCorporation oracle = south.addCorporation("Oracle", Color.RED); for (int i = 0; i < 8; i++) { campaign.addRound(); } player2.addCampaign(campaign); player3.addCampaign(campaign); em.persist(campaign); Team t1 = new Team("anoym1"); Team t2 = new Team("anoym2"); Team t3 = new Team("anoym3"); t1.addCorporation(ibm); t2.addCorporation(ericsson); t3.addCorporation(oracle); em.persist(t1); em.persist(t2); em.persist(t3); Campaign runningCampaign = teacher.createCampagin("", Campaign.Type.COURSE); SimMarket m1 = runningCampaign.addMarket(""); SimMarket m2 = runningCampaign.addMarket(""); SimMarket m3 = runningCampaign.addMarket(""); SimCorporation corp1 = m1.addCorporation("", Color.ORANGE); for (int i = 0; i < 3; i++) { runningCampaign.addRound(); } player1.addCampaign(runningCampaign); player2.addCampaign(runningCampaign); player3.addCampaign(runningCampaign); runningCampaign.setStatus(Campaign.Status.ONGOING); Team t11 = new Team("anoym11"); t11.addCorporation(corp1); t11.addUser(player1); t11.addUser(player2); t11.addUser(player3); em.persist(t11); tx.commit(); } finally { em.close(); } }
From source file:org.opencastproject.messages.MailService.java
public static MessageTemplateDto mergeMessageTemplate(MessageTemplate template, String organization, EntityManager em) { ArrayList<CommentDto> comments = new ArrayList<CommentDto>(); for (Comment c : template.getComments()) { comments.add(CommentDatabaseUtils.mergeComment(c, em)); }//from w ww. j a v a2 s. c o m Option<MessageTemplateDto> dtoOption = findMessageTemplate(option(template.getId()), template.getName(), organization, em); MessageTemplateDto dto; if (dtoOption.isSome()) { dto = dtoOption.get(); dto.setName(template.getName()); dto.setType(template.getType().getType()); dto.setCreator(template.getCreator().getUsername()); dto.setSubject(template.getSubject()); dto.setBody(template.getBody()); dto.setCreationDate(template.getCreationDate()); dto.setComments(comments); dto.setHidden(template.isHidden()); em.merge(dto); } else { dto = new MessageTemplateDto(template.getName(), organization, template.getCreator().getUsername(), template.getSubject(), template.getBody(), template.getType().getType(), template.getCreationDate(), comments); dto.setHidden(template.isHidden()); em.persist(dto); } return dto; }
From source file:uk.ac.edukapp.service.UserAccountService.java
public WidgetFavourite addFavourite(Useraccount user, Widgetprofile favourite, int level) { EntityManager em = getEntityManagerFactory().createEntityManager(); em.getTransaction().begin();//ww w . j av a 2 s . co m WidgetFavourite widgetFavourite = null; // check to see if it exists try { Query q = em.createNamedQuery("favourite.select"); q.setParameter("user", user); q.setParameter("widgetprofile", favourite); widgetFavourite = (WidgetFavourite) q.getSingleResult(); if (widgetFavourite != null) { widgetFavourite.setRelevance(level); } } catch (NoResultException exp) { // fine just make one widgetFavourite = new WidgetFavourite(); widgetFavourite.setUserAccount(user); widgetFavourite.setWidgetProfile(favourite); widgetFavourite.setRelevance(level); em.persist(widgetFavourite); } em.getTransaction().commit(); em.close(); return widgetFavourite; }
From source file:com.headissue.pigeon.survey.answer.AnswerHandler.java
private void storeAnswer(Survey _survey, Question _question, UserMap map, UserAnswerValue _value, EntityManager _manager, Date _timestamp) { TypedQuery<Answer> q = _manager.createNamedQuery("answer.findAnswerBySurveyQuestionAndUserMap", Answer.class); q.setParameter("survey", _survey); q.setParameter("question", _question); q.setParameter("userMap", map); Answer _answer = JPAUtils.getSingleResult(q); if (_answer == null) { _answer = new Answer(); _answer.setTimestamp(_timestamp); _answer.setSurvey(_survey);// w w w. j av a2 s . co m _answer.setQuestion(_question); _answer.setUserMap(map); } else { _answer.getAnswerValues().clear(); _answer.getAnswerTexts().clear(); } AnswerTransform _transform = transformFactory.get(_question.getType().toString()); if (_transform.transfer(_answer, _value)) { _manager.persist(_answer); } else { LogUtils.warn(log, "store answer is failed (surveyId=%s, questionId=%s, questionType=%s) user answer '%s'", _survey.getId(), _question.getId(), _question.getType(), _value); } }
From source file:org.traccar.web.server.model.DataServiceImpl.java
@Override public User addUser(User user) { User currentUser = getSessionUser(); if (user.getLogin().isEmpty() || user.getPassword().isEmpty()) { throw new IllegalArgumentException(); }/* ww w. j a va2s .c o m*/ if (currentUser.getAdmin()) { EntityManager entityManager = getSessionEntityManager(); synchronized (entityManager) { entityManager.getTransaction().begin(); try { entityManager.persist(user); entityManager.getTransaction().commit(); return user; } catch (RuntimeException e) { entityManager.getTransaction().rollback(); throw e; } } } else { throw new SecurityException(); } }
From source file:com.sun.socialsite.business.impl.DefaultUserCreator.java
private void createSocialSiteUser(String id) throws UserManagementException { EntityManager em = null; User user = null;//from ww w . jav a 2s .co m try { em = strategy.getEntityManager(false); UserManager userManager = new UserManagerImpl(em); user = userManager.getUserByUserId(id); if (user == null) { Date now = new Date(); user = new User(); user.setUserId(id); user.setUserName(id); user.resetPassword(id, "SHA"); user.setFullName(id); user.setEmailAddress(id + "@sun.com"); user.setCreationDate(now); user.setUpdateDate(now); user.setAccessDate(now); user.setEnabled(true); em.getTransaction().begin(); try { userManager.registerUser(user); userManager.grantRole("user", user); em.persist(user); } catch (Throwable t) { try { if (em.getTransaction().isActive()) em.getTransaction().rollback(); } catch (Throwable t2) { log.error("Failed to rollback transaction: " + em.getTransaction(), t2); } throw new UserManagementException(t); } em.getTransaction().commit(); } } finally { try { if (em != null) { em.close(); } } catch (Throwable t) { throw new UserManagementException(t); } } }
From source file:pl.datamatica.traccar.api.fcm.Daemon.java
protected void sendToFcm(EntityManager em, FcmNotificationDto dto) { Gson gson = Context.getInstance().getGson(); String message = gson.toJson(dto); String result = sendToFcm(message); boolean success = false; if (result != null) { try {//from w w w .j a va 2 s . c o m JsonParser parser = new JsonParser(); JsonObject o = parser.parse(result).getAsJsonObject(); success = o.get("success").getAsInt() == 1; if (!success) Logger.getLogger(Daemon.class.getName()).log(Level.INFO, o.getAsJsonArray("results").toString()); } catch (Exception e) { // Probably incorrect fcm scret -> incorrect response JSON Logger.getLogger(Daemon.class.getName()).log(Level.INFO, e.getLocalizedMessage()); } } NotificationStatus ns = new NotificationStatus(dto.getTo(), dto.getKind(), success); em.persist(ns); }
From source file:org.traccar.web.server.model.DataServiceImpl.java
@Override public Device addDevice(Device device) { EntityManager entityManager = getSessionEntityManager(); synchronized (entityManager) { User user = getSessionUser();/*from www. ja v a 2 s.c o m*/ entityManager.getTransaction().begin(); try { entityManager.persist(device); user.getDevices().add(device); entityManager.getTransaction().commit(); return device; } catch (RuntimeException e) { entityManager.getTransaction().rollback(); throw e; } } }
From source file:com.adeptj.modules.data.jpa.core.AbstractJpaRepository.java
@Override public <T extends BaseEntity> void batchInsert(List<T> entities, int batchSize) { Validate.isTrue(entities != null && !entities.isEmpty() && batchSize > 1, "Invalid inputs!!"); EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory()); try {/*from w w w .j a v a 2 s.c o m*/ em.getTransaction().begin(); for (int index = 0; index < entities.size(); index++) { if (index > 0 && index % batchSize == 0) { em.getTransaction().commit(); em.getTransaction().begin(); em.clear(); } em.persist(entities.get(index)); } em.getTransaction().commit(); } catch (Exception ex) { // NOSONAR Transactions.markRollback(em); throw new JpaException(ex); } finally { Transactions.rollback(em); JpaUtil.closeEntityManager(em); } }