List of usage examples for javax.persistence EntityManager persist
public void persist(Object entity);
From source file:org.opencastproject.usertracking.impl.UserTrackingServiceImpl.java
@SuppressWarnings("unchecked") public UserAction addUserFootprint(UserAction a) throws UserTrackingException { a.setType("FOOTPRINT"); EntityManager em = null; EntityTransaction tx = null;// w w w .j a v a 2 s . c o m try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); Query q = em.createNamedQuery("findLastUserFootprintOfSession"); q.setMaxResults(1); q.setParameter("sessionId", a.getSessionId()); Collection<UserAction> userActions = q.getResultList(); if (userActions.size() >= 1) { UserAction last = userActions.iterator().next(); if (last.getMediapackageId().equals(a.getMediapackageId()) && last.getType().equals(a.getType()) && last.getOutpoint() == a.getInpoint()) { last.setOutpoint(a.getOutpoint()); a = last; a.setId(last.getId()); } else { em.persist(a); } } else { em.persist(a); } tx.commit(); return a; } catch (Exception e) { if (tx != null && tx.isActive()) { tx.rollback(); } throw new UserTrackingException(e); } finally { if (em != null && em.isOpen()) { em.close(); } } }
From source file:com.jada.admin.site.SiteLoader.java
public void loadCreditCard() throws Exception { EntityManager em = JpaConnection.getInstance().getCurrentEntityManager(); String sql = "from CreditCard where siteId = :siteId order by creditCardId"; Query query = em.createQuery(sql); query.setParameter("siteId", Constants.SITE_SYSTEM); Iterator<?> iterator = query.getResultList().iterator(); while (iterator.hasNext()) { CreditCard master = (CreditCard) iterator.next(); CreditCard creditCard = new CreditCard(); PropertyUtils.copyProperties(creditCard, master); creditCard.setSite(site);//from www.jav a2 s .co m creditCard.setCreditCardId(null); creditCard.setRecUpdateBy(userId); creditCard.setRecUpdateDatetime(new Date(System.currentTimeMillis())); creditCard.setRecCreateBy(userId); creditCard.setRecCreateDatetime(new Date(System.currentTimeMillis())); em.persist(creditCard); } }
From source file:org.sigmah.server.endpoint.export.sigmah.handler.ProjectModelHandler.java
/** * Save the flexible elements of imported project model. * //from w w w . j a v a 2 s. c o m * @param projectModel * the imported project model * @param em * the entity manager */ private void saveProjectFlexibleElement(ProjectModel projectModel, EntityManager em, HashMap<Object, Object> modelesReset, HashSet<Object> modelesImport, Authentication authentication) { // ProjectModel --> Banner --> Layout --> Groups --> Constraints if (projectModel.getProjectBanner() != null && projectModel.getProjectBanner().getLayout() != null) { final List<LayoutGroup> bannerLayoutGroups = projectModel.getProjectBanner().getLayout().getGroups(); saveLayoutGroups(bannerLayoutGroups, em, modelesReset, modelesImport, authentication); } // ProjectModel --> Detail --> Layout --> Groups --> Constraints if (projectModel.getProjectDetails() != null && projectModel.getProjectDetails().getLayout() != null) { final List<LayoutGroup> detailLayoutGroups = projectModel.getProjectDetails().getLayout().getGroups(); saveLayoutGroups(detailLayoutGroups, em, modelesReset, modelesImport, authentication); } // ProjectModel --> Phases --> Layout --> Groups --> Constraints List<PhaseModel> phases = projectModel.getPhases(); if (phases != null) { projectModel.setPhases(null); em.persist(projectModel); for (PhaseModel phase : phases) { phase.setParentProjectModel(projectModel); if (phase.getLayout() != null) { final List<LayoutGroup> phaseLayoutGroups = phase.getLayout().getGroups(); saveLayoutGroups(phaseLayoutGroups, em, modelesReset, modelesImport, authentication); } if (phase.getDefinition() != null) { em.persist(phase.getDefinition()); } em.persist(phase); } projectModel.setPhases(phases); } }
From source file:org.sigmah.server.servlet.exporter.models.ProjectModelHandler.java
/** * Save the flexible elements of imported project model. * /* w w w .j av a 2 s . co m*/ * @param projectModel * the imported project model * @param em * the entity manager */ private void saveProjectFlexibleElement(ProjectModel projectModel, EntityManager em, HashMap<Object, Object> modelesReset, HashSet<Object> modelesImport, User user) { // ProjectModel --> Banner --> Layout --> Groups --> Constraints if (projectModel.getProjectBanner() != null && projectModel.getProjectBanner().getLayout() != null) { final List<LayoutGroup> bannerLayoutGroups = projectModel.getProjectBanner().getLayout().getGroups(); saveLayoutGroups(bannerLayoutGroups, em, modelesReset, modelesImport, user); } // ProjectModel --> Detail --> Layout --> Groups --> Constraints if (projectModel.getProjectDetails() != null && projectModel.getProjectDetails().getLayout() != null) { final List<LayoutGroup> detailLayoutGroups = projectModel.getProjectDetails().getLayout().getGroups(); saveLayoutGroups(detailLayoutGroups, em, modelesReset, modelesImport, user); } // ProjectModel --> Phases --> Layout --> Groups --> Constraints List<PhaseModel> phases = projectModel.getPhaseModels(); if (phases != null) { projectModel.setPhaseModels(null); em.persist(projectModel); for (PhaseModel phase : phases) { phase.setParentProjectModel(projectModel); if (phase.getLayout() != null) { final List<LayoutGroup> phaseLayoutGroups = phase.getLayout().getGroups(); saveLayoutGroups(phaseLayoutGroups, em, modelesReset, modelesImport, user); } if (phase.getDefinition() != null) { em.persist(phase.getDefinition()); } em.persist(phase); } projectModel.setPhaseModels(phases); } }
From source file:uk.ac.edukapp.service.WidgetProfileService.java
/** * Create a widget profile and save it/*from w ww .ja v a2 s. c om*/ * * @param uri * @param name * @param description * @return the widget profile */ public Widgetprofile createWidgetProfile(String uri, String name, String description, String icon, String type, Useraccount owner) { EntityManager em = getEntityManagerFactory().createEntityManager(); em.getTransaction().begin(); Widgetprofile widgetprofile = new Widgetprofile(); widgetprofile.setName(name); widgetprofile.setCreated(new Date()); widgetprofile.setUpdated(new Date()); widgetprofile.setIcon(icon); widgetprofile.setOwner(owner); widgetprofile.setUpdated(new Date()); widgetprofile.setIcon(icon); byte zero = 0; byte one = 1; if (type.equals(Widgetprofile.W3C_WIDGET)) { widgetprofile.setW3cOrOs(zero); } else { widgetprofile.setW3cOrOs(one); } widgetprofile.setWidId(uri); em.persist(widgetprofile); WidgetDescription wd = new WidgetDescription(); wd.setDescription(description); wd.setWid_id(widgetprofile.getId()); em.persist(wd); // // Create the widget stats // WidgetStats widgetStats = new WidgetStats(); widgetStats.setWid_id(widgetprofile.getId()); widgetStats.setDownloads(0); widgetStats.setEmbeds(0); widgetStats.setViews(0); em.persist(widgetStats); em.getTransaction().commit(); em.close(); return widgetprofile; }
From source file:org.artificer.repository.hibernate.HibernatePersistenceManager.java
@Override public BaseArtifactType updateArtifact(final BaseArtifactType srampArtifact, final ArtifactType artifactType) throws ArtificerException { ArtificerArtifact artificerArtifact = new HibernateUtil.HibernateTask<ArtificerArtifact>() { @Override// w ww . ja va 2 s . co m protected ArtificerArtifact doExecute(EntityManager entityManager) throws Exception { ArtificerArtifact artificerArtifact = HibernateUtil.getArtifact(srampArtifact.getUuid(), entityManager, true); HibernateUtil.evict(ArtificerArtifact.class, artificerArtifact.getId(), entityManager); HibernateAuditor differ = null; if (ArtificerConfig.isAuditingEnabled()) { differ = new HibernateAuditor(artificerArtifact); } SrampToHibernateEntityVisitor.visit(srampArtifact, artificerArtifact, artifactType, classificationHelper); HibernateRelationshipFactory relationshipFactory = new HibernateRelationshipFactory(); SrampToHibernateEntityRelationshipsVisitor.visit(srampArtifact, artificerArtifact, relationshipFactory, entityManager); if (ArtificerConfig.isAuditingEnabled()) { ArtificerAuditEntry auditEntry = differ.diff(artificerArtifact); entityManager.persist(auditEntry); } return artificerArtifact; } }.execute(); try { return HibernateEntityToSrampVisitor.visit(artificerArtifact, artifactType, true); } catch (ArtificerException ae) { throw ae; } catch (Throwable t) { throw new ArtificerServerException(t); } }
From source file:org.apache.juddi.api.impl.JUDDIApiImpl.java
/** * Saves nodes(s) to the persistence layer. This method is specific to * jUDDI. Administrative privilege required. This is used for server to server subscriptions and for future use * with replication. Administrative privilege required. * @param body//from w w w . j a va 2s . c o m * @return NodeDetail * @throws DispositionReportFaultMessage */ public NodeDetail saveNode(SaveNode body) throws DispositionReportFaultMessage { EntityManager em = PersistenceManager.getEntityManager(); EntityTransaction tx = em.getTransaction(); try { tx.begin(); UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); new ValidateNode(publisher).validateSaveNode(em, body); NodeDetail result = new NodeDetail(); List<org.apache.juddi.api_v3.Node> apiNodeList = body.getNode(); ; for (org.apache.juddi.api_v3.Node apiNode : apiNodeList) { org.apache.juddi.model.Node modelNode = new org.apache.juddi.model.Node(); MappingApiToModel.mapNode(apiNode, modelNode); Object existingUddiEntity = em.find(modelNode.getClass(), modelNode.getName()); if (existingUddiEntity != null) { em.merge(modelNode); } else { em.persist(modelNode); } result.getNode().add(apiNode); } tx.commit(); return result; } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } }
From source file:org.apereo.portal.portlet.dao.jpa.JpaMarketplaceRatingDao.java
@Override @PortalTransactional//from w ww . ja va 2s . c o m public void aggregateMarketplaceRating() { //setup EntityManager em = this.getEntityManager(); //get list of average ratings Query aggregatedQuery = em.createQuery("SELECT AVG(m.rating) as rating, " + " count(m.marketplaceRatingPK.portletDefinition.internalPortletDefinitionId) as theCount, " + " m.marketplaceRatingPK.portletDefinition.internalPortletDefinitionId as portletId " + " FROM MarketplaceRatingImpl m " + " GROUP BY m.marketplaceRatingPK.portletDefinition.internalPortletDefinitionId"); @SuppressWarnings("unchecked") List<Object[]> aggregatedResults = aggregatedQuery.getResultList(); //update the portlet definition with the average rating for (Object[] result : aggregatedResults) { if (result != null && result.length == 3) { try { Double averageRating = (Double) result[0]; Long usersRated = (Long) result[1]; String portletId = ((Long) result[2]).toString(); IPortletDefinition portletDefinition = portletDefinitionDao.getPortletDefinition(portletId); if (portletDefinition != null) { portletDefinition.setRating(averageRating); portletDefinition.setUsersRated(usersRated); em.persist(portletDefinition); } } catch (Exception ex) { logger.warn("Issue aggregating portlet ratings, recoverable", ex); } } } }
From source file:com.jada.admin.site.SiteLoader.java
public void loadMenu() throws Exception { EntityManager em = JpaConnection.getInstance().getCurrentEntityManager(); String sql = "from Menu where siteId = :siteId order by menuSetName"; Query query = em.createQuery(sql); query.setParameter("siteId", Constants.SITE_SYSTEM); Iterator<?> iterator = query.getResultList().iterator(); while (iterator.hasNext()) { Menu master = (Menu) iterator.next(); Menu menu = new Menu(); PropertyUtils.copyProperties(menu, master); // menu.setSite(site); menu.setMenuId(null);//from w w w. ja v a 2 s .c o m menu.setRecUpdateBy(userId); menu.setRecUpdateDatetime(new Date(System.currentTimeMillis())); menu.setRecCreateBy(userId); menu.setRecCreateDatetime(new Date(System.currentTimeMillis())); menu.setCategory(null); menu.setContent(null); menu.setItem(null); menu.setMenuLanguages(null); em.persist(menu); } }
From source file:de.zib.gndms.logic.model.TaskAction.java
/** * Retrieves the current model and checks if its lifetime is already exceeded. * In this case the model's TaskState will be set to {@code failed} and a {@link FailedException} is thrown, * which will stop the the main loop in {@code execute()}. * * Otherwise, the model's TaskState is set to {@code newState} and {@link #transit(TaskState, AbstractTask)} * will be invoked,//w w w . j a v a 2s.c om * which calls a method corresponding to the TaskState {@code newState} and throws a {@code TransitException} after its * execution specifying the next TaskSate value for the model. * * The model is made persistent by the EntityManager and the changed model will be * commited to the database. * If something goes wrong while commiting the new model, a stable rollback is assured. * * @param newState the new TaskState for the model */ @SuppressWarnings({ "CaughtExceptionImmediatelyRethrown", "ThrowableInstanceNeverThrown" }) private void transit(final TaskState newState) { if (getCancelled()) { log.debug("cancelled"); throw new StopException(TaskState.IN_PROGRESS_UNKNOWN); } EntityManager em = getEntityManager(); @NotNull AbstractTask model = getModel(); // this throws a stop exception on timeout if (!(TaskState.FINISHED.equals(newState) || TaskState.FAILED.equals(newState))) checkTimeout(model, em); try { em.getTransaction().begin(); if (newState != null) { if (!em.contains(model)) { log.debug("model not in EntityManager"); try { try { em.persist(model); } catch (EntityExistsException e) { log.debug("persisting failed merging", e); rewindTransaction(em.getTransaction()); em.merge(model); } } catch (RuntimeException e2) { log.debug("probably persisting and merging failed", e2); rewindTransaction(em.getTransaction()); final @NotNull AbstractTask newModel = em.find(AbstractTask.class, model.getId()); model.mold(newModel); newModel.refresh(em); setModel(newModel); model = getModel(); log.debug("completed renewing of model"); } } } model.transit(newState); boolean committed = false; try { em.getTransaction().commit(); // em.flush( ); committed = true; } catch (Exception e) { log.debug("commit of transit (" + newState.name() + ") model failed ", e); try { rewindTransaction(em.getTransaction()); // if this point is reached s.th. is terribly foobared // restore backup and fail model = Copier.copy(false, backup); em.merge(model); // backup should be clean so commit mustn't fail. model.fail(e); em.getTransaction().commit(); } catch (Exception e2) { log.debug("restoring previous version failed", e2); try { // refresh em for final commit EntityManagerAux.rollbackAndClose(em); } catch (RuntimeException e3) { log.debug("rollback old em failed", e3); } EntityManager nem = emf.createEntityManager(); TxFrame tx = new TxFrame(nem); try { log.debug("loading fresh model"); model = nem.find(model.getClass(), backup.getId()); boolean unkown = (model == null); model = Copier.copy(false, backup); model.fail(e2); if (unkown) nem.persist(model); // else // nem.merge( model ); tx.commit(); setModel(model); } catch (RuntimeException e3) { log.debug("exception during refresh: ", e3); throw e3; } finally { tx.finish(); setOwnEntityManager(nem); em = nem; } } } // if model could be commited it has a clean state // refresh backup if (committed) setBackup(Copier.copy(false, model)); final TaskState modelState = model.getState(); refreshTaskResource(); //noinspection HardcodedFileSeparator trace("on" + modelState + "()", null); transit(modelState, model); } // for debugging catch (RuntimeException e) { throw e; } finally { try { // for debuggin' boolean ta = em.getTransaction().isActive(); if (ta) { log.debug("final rollback"); em.getTransaction().rollback(); } } catch (Exception e) { log.debug("final rollback failed", e); } } }