List of usage examples for javax.persistence EntityManager persist
public void persist(Object entity);
From source file:eu.clarin.cmdi.virtualcollectionregistry.VirtualCollectionRegistryMaintenanceImpl.java
/** * Assign a PID for this VirtualCollection. * // w ww .j a va 2 s . c o m * @param em * @param vc */ protected void allocatePersistentIdentifier(EntityManager em, VirtualCollection vc) { VirtualCollection.State currentState = vc.getState(); logger.info("Found {} with state {}", vc.getName(), currentState); if (!vc.hasPersistentIdentifier()) { try { PersistentIdentifier pid = pid_provider.createIdentifier(vc); vc.setPersistentIdentifier(pid); } catch (VirtualCollectionRegistryException ex) { logger.error("Failed to mint PID, setting vc to error state"); vc.setState(VirtualCollection.State.ERROR); if (ex.getCause() instanceof HttpException) { vc.setProblem(VirtualCollection.Problem.PID_MINTING_UNKOWN); } else { vc.setProblem(VirtualCollection.Problem.PID_MINTING_UNKOWN); } } } em.persist(vc); if (vc.hasPersistentIdentifier()) { logger.info("assigned pid (identifer='{}') to virtual" + "collection (id={})", vc.getPersistentIdentifier().getIdentifier(), vc.getId()); } }
From source file:org.artificer.repository.hibernate.HibernatePersistenceManager.java
@Override public BaseArtifactType addComment(final String uuid, final ArtifactType artifactType, final String text) throws ArtificerException { return new HibernateUtil.HibernateTask<BaseArtifactType>() { @Override/*from w w w.j a v a 2s .c om*/ protected BaseArtifactType doExecute(EntityManager entityManager) throws Exception { ArtificerArtifact artifact = HibernateUtil.getArtifact(uuid, entityManager, false); HibernateUtil.evict(ArtificerArtifact.class, artifact.getId(), entityManager); ArtificerComment comment = new ArtificerComment(); comment.setCreatedBy(HibernateEntityFactory.user()); comment.setText(text); comment.setArtifact(artifact); entityManager.persist(comment); return HibernateEntityToSrampVisitor.visit(artifact, artifactType, true); } }.execute(); }
From source file:com.gigglinggnus.controllers.ModifyAppointmentController.java
/** * * @param request servlet request//from w w w. java 2 s .co m * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { EntityManager em = (EntityManager) request.getSession().getAttribute("em"); Clock clk = (Clock) (request.getSession().getAttribute("clock")); boolean modified = false; String userId = request.getParameter("userid"); User user = em.find(User.class, userId); String examId = request.getParameter("examid"); Exam exam = em.find(Exam.class, examId); Appointment appt = user.getAppointmentByExam(exam); String startTime = request.getParameter("startTime"); String seatZone = request.getParameter("seatingZone"); String seatNum = request.getParameter("seatNum"); String cancel = request.getParameter("cancel"); try { em.getTransaction().begin(); if (startTime != "") { appt.changeStartTime(Instant.parse(startTime), clk); em.persist(appt); modified = true; } if (seatZone != "") { appt.setSeatingZone(Seating.parse(seatZone)); em.persist(appt); modified = true; } if (seatNum != "") { appt.setSeatNum(Integer.parseInt(seatNum)); em.persist(appt); modified = true; } em.getTransaction().commit(); } catch (Exception e) { em.getTransaction().rollback(); request.setAttribute("msg", e); RequestDispatcher rd = request.getRequestDispatcher("/home.jsp"); rd.forward(request, response); } if (cancel != null) { request.setAttribute("msg", "Appointment cancelled"); RequestDispatcher rd = request.getRequestDispatcher("/home.jsp"); rd.forward(request, response); } if (modified == true) { request.setAttribute("msg", "Appointment modified"); RequestDispatcher rd = request.getRequestDispatcher("/home.jsp"); rd.forward(request, response); } else { request.setAttribute("msg", "Appointment unchanged"); RequestDispatcher rd = request.getRequestDispatcher("/home.jsp"); rd.forward(request, response); } }
From source file:kirchnerei.note.model.DataService.java
public Long storeNote(NoteData noteData) { EntityManager em = null; EntityTransaction tx = null;/*from w w w . jav a2s . c o m*/ try { em = entityService.get(); tx = em.getTransaction(); tx.begin(); // search for category String category = noteData.getCategory(); if (StringUtils.isEmpty(category)) { LogUtils.warn(log, "note without category is not allow [%s]", noteData); return null; } TypedQuery<Category> q = em.createNamedQuery("findCategory", Category.class); q.setParameter("category", category); Category cat = getSingleResult(q); if (cat == null) { // a new category cat = new Category(); cat.setTitle(category); em.persist(cat); } final Note note; if (NumberUtils.isEmpty(noteData.getId())) { // create a new note note = beanCopy.copy(noteData, Note.class, noteProperties); note.setCategory(cat); cat.getNotes().add(note); } else { // update an existed note note = em.find(Note.class, noteData.getId()); beanCopy.copy(noteData, note, noteProperties); if (!NumberUtils.compare(note.getCategory().getId(), cat.getId())) { // move to other category note.getCategory().getNotes().remove(note); cat.getNotes().add(note); note.setCategory(cat); } } EntityService.commit(tx); return note.getId(); } catch (Exception e) { EntityService.rollback(tx); return null; } finally { EntityService.close(em); } }
From source file:org.traccar.web.server.model.DataServiceImpl.java
private void createUser(EntityManager entityManager, User user) { synchronized (entityManager) { entityManager.getTransaction().begin(); try {//from w w w .j a v a 2s .c o m entityManager.persist(user); entityManager.getTransaction().commit(); } catch (RuntimeException e) { entityManager.getTransaction().rollback(); throw e; } } }
From source file:org.opencastproject.themes.persistence.ThemesServiceDatabaseImpl.java
@Override public Theme updateTheme(Theme theme) throws ThemesServiceDatabaseException { EntityManager em = null; EntityTransaction tx = null;//from ww w . j ava2 s . co m try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); ThemeDto themeDto = null; if (theme.getId().isSome()) themeDto = getThemeDto(theme.getId().get(), em); if (themeDto == null) { // no theme stored, create new entity themeDto = new ThemeDto(); themeDto.setOrganization(securityService.getOrganization().getId()); updateTheme(theme, themeDto); em.persist(themeDto); } else { updateTheme(theme, themeDto); em.merge(themeDto); } tx.commit(); theme = themeDto.toTheme(userDirectoryService); messageSender.sendObjectMessage(ThemeItem.THEME_QUEUE, MessageSender.DestinationType.Queue, ThemeItem.update(toSerializableTheme(theme))); return theme; } catch (Exception e) { logger.error("Could not update theme {}: {}", theme, ExceptionUtils.getStackTrace(e)); if (tx.isActive()) { tx.rollback(); } throw new ThemesServiceDatabaseException(e); } finally { if (em != null) { em.close(); } } }
From source file:uk.ac.edukapp.service.WidgetProfileService.java
/** * Update the description associated with a widget profile * //w ww . j a v a 2 s . com * @param widgetProfile * @param text */ private void updateDescription(Widgetprofile widgetProfile, String text) { WidgetDescription widget_desc = widgetProfile.getDescription(); if (widget_desc == null) { widget_desc = new WidgetDescription(); widget_desc.setWid_id(widgetProfile.getId()); } widget_desc.setDescription(text); widgetProfile.setDescription(widget_desc); EntityManager entityManager = getEntityManagerFactory().createEntityManager(); entityManager.getTransaction().begin(); entityManager.persist(entityManager.merge(widgetProfile)); entityManager.getTransaction().commit(); entityManager.close(); }
From source file:nl.b3p.viewer.admin.stripes.GeoServiceRegistryActionBean.java
public Resolution addSubcategory() throws JSONException { EntityManager em = Stripersist.getEntityManager(); JSONObject json = new JSONObject(); json.put("success", Boolean.FALSE); String error = checkCategoryAndNameError(); if (error == null) { for (Category child : category.getChildren()) { if (name.equals(child.getName())) { error = "Categorie met dezelfde naam bestaat al"; }/*from ww w. java2 s .co m*/ } } if (error == null) { try { Category c = new Category(); c.setName(name); c.setParent(category); category.getChildren().add(c); em.persist(c); em.getTransaction().commit(); JSONObject node = new JSONObject(); node.put("id", "c" + c.getId()); node.put("name", c.getName()); node.put("type", "category"); node.put("isLeaf", true); node.put("parentid", nodeId); json.put("node", node); json.put("success", Boolean.TRUE); } catch (Exception e) { log.error("Fout bij toevoegen categorie", e); error = "Kan categorie niet toevoegen: " + e; Throwable t = e; while (t.getCause() != null) { t = t.getCause(); error += "; " + t; } } } if (error != null) { json.put("error", error); } return new StreamingResolution("application/json", new StringReader(json.toString())); }
From source file:org.opencastproject.capture.admin.impl.CaptureAgentStateServiceImpl.java
/** * Updates or adds an agent to the database. * /* ww w .j a v a2 s .co m*/ * @param agent * The Agent you wish to modify or add in the database. */ protected void updateAgentInDatabase(AgentImpl agent) { EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); AgentImpl existing = getAgentEntity(agent.getName(), agent.getOrganization(), em); if (existing == null) { em.persist(agent); } else { existing.setConfiguration(agent.getConfiguration()); existing.setLastHeardFrom(agent.getLastHeardFrom()); existing.setState(agent.getState()); existing.setSchedulerRoles(agent.getSchedulerRoles()); existing.setUrl(agent.getUrl()); em.merge(existing); } tx.commit(); agentCache.put(agent.getName().concat(DELIMITER).concat(agent.getOrganization()), Tuple.tuple(agent.getState(), agent.getConfiguration())); } catch (RollbackException e) { logger.warn("Unable to commit to DB in updateAgent."); throw e; } finally { if (em != null) em.close(); } }
From source file:org.apache.juddi.v3.auth.JUDDIAuthenticator.java
/** * @return the userId that came in on the request providing the user has * a publishing account in jUDDI./*from w w w . j a v a2 s . c o m*/ * @param authorizedName * @param credential * @return authorizedName * @throws AuthenticationException */ public String authenticate(String authorizedName, String credential) throws AuthenticationException { if (authorizedName == null || "".equals(authorizedName)) { throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName)); } log.warn("DO NOT USE JUDDI AUTHENTICATOR FOR PRODUCTION SYSTEMS - DOES NOT VALIDATE PASSWORDS, AT ALL!"); 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; log.error("config exception! " + authorizedName, ex); } EntityManager em = PersistenceManager.getEntityManager(); EntityTransaction tx = em.getTransaction(); try { tx.begin(); Publisher publisher = em.find(Publisher.class, authorizedName); if (publisher == null) { log.warn("Publisher \"" + authorizedName + "\" 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(); } return authorizedName; } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } }