List of usage examples for javax.persistence EntityManager persist
public void persist(Object entity);
From source file:org.eclipse.jubula.client.core.persistence.ProjectPM.java
/** * Persists the given project to the DB. This is performed in a new session. * When this method returns, the project will not be attached to any session. * @param proj ProjectPO to be saved./*from w w w .ja va 2 s . co m*/ * @param newProjectName * name part of the ProjectNamePO. If there is no new name, this * parameter must be null (same project, different version) * @param mapperList a List of INameMapper to persist names (Parameter). * @param compNameBindingList a List of Component Name mappers to persist * names (Component). * @throws PMException in case of any db error * @throws ProjectDeletedException if project is already deleted * @throws InterruptedException if the operation is canceled */ public static void saveProject(IProjectPO proj, String newProjectName, List<INameMapper> mapperList, List<IWritableComponentNameMapper> compNameBindingList) throws PMException, ProjectDeletedException, InterruptedException { final EntityManager saveSession = Persistor.instance().openSession(); EntityTransaction tx = null; try { tx = Persistor.instance().getTransaction(saveSession); saveSession.persist(proj); proj.setParentProjectId(proj.getId()); saveSession.flush(); if (newProjectName != null) { ProjectNameBP.getInstance().setName(saveSession, proj.getGuid(), newProjectName); } ProjectNameBP.getInstance().storeTransientNames(saveSession); for (INameMapper mapper : mapperList) { mapper.persist(saveSession, proj.getId()); } for (IWritableComponentNameMapper compNameBinding : compNameBindingList) { CompNamePM.flushCompNames(saveSession, proj.getId(), compNameBinding); } Persistor.instance().commitTransaction(saveSession, tx); for (INameMapper mapper : mapperList) { mapper.updateStandardMapperAndCleanup(proj.getId()); } for (IComponentNameMapper compNameCache : compNameBindingList) { compNameCache.getCompNameCache().updateStandardMapperAndCleanup(proj.getId()); } } catch (PersistenceException e) { if (tx != null) { Persistor.instance().rollbackTransaction(saveSession, tx); } if (e.getCause() instanceof InterruptedException) { // Operation was canceled. throw new InterruptedException(); } String msg = Messages.CantSaveProject + StringConstants.DOT; throw new PMSaveException(msg + e.getMessage(), MessageIDs.E_ATTACH_PROJECT); } catch (IncompatibleTypeException ite) { if (tx != null) { Persistor.instance().rollbackTransaction(saveSession, tx); } String msg = Messages.CantSaveProject + StringConstants.DOT; throw new PMSaveException(msg + ite.getMessage(), MessageIDs.E_ATTACH_PROJECT); } finally { Persistor.instance().dropSession(saveSession); } }
From source file:BO.UserHandler.java
public boolean login(VUser u) { EntityManager em; EntityManagerFactory emf;// ww w .j ava 2 s .c om emf = Persistence.createEntityManagerFactory(PERSISTENCE_NAME); em = emf.createEntityManager(); try { Query q = em.createQuery("SELECT u FROM User u WHERE u.email LIKE :email"); q.setParameter("email", u.getEmail()); q.setMaxResults(1); q.getSingleResult(); return true; } catch (NoResultException e) { em.getTransaction().begin(); User userToInsert = new User(u.getEmail()); em.persist(userToInsert); em.flush(); em.getTransaction().commit(); return true; } finally { if (em != null) { em.close(); } emf.close(); } }
From source file:BO.UserHandler.java
public boolean updateDeviceToken(VUser u) { EntityManager em; EntityManagerFactory emf;/*from w ww.j a v a 2s . c om*/ emf = Persistence.createEntityManagerFactory(PERSISTENCE_NAME); em = emf.createEntityManager(); System.out.println("Updating token: " + u.getDeviceToken()); try { em.getTransaction().begin(); User user; user = (User) em.createQuery("SELECT u FROM User u WHERE u.email LIKE :email") .setParameter("email", u.getEmail()).setMaxResults(1).getSingleResult(); user.setDeviceToken(u.getDeviceToken()); em.persist(user); em.flush(); em.getTransaction().commit(); return true; } catch (NoResultException e) { return false; } finally { if (em != null) { em.close(); } emf.close(); } }
From source file:de.egore911.opengate.services.GameserverService.java
@GET @Path("/add") @Produces("application/json") @Documentation("Add or update a gameserver to the list of available game servers. " + "The remote IP will be obtained from the packet sent to the server so server " + "behind a NAT will not work. The method will answer using a JSON object like " + "{status: 'ok', detail: '...'}.") public Response addGameserver(@Context HttpServletRequest req) { String remoteAddr = req.getRemoteAddr(); EntityManager em = EntityManagerFilter.getEntityManager(); Gameserver gameserver;// ww w .j ava2 s . c o m try { JSONObject retval = new JSONObject(); StatusHelper.ok(retval); try { gameserver = (Gameserver) em .createQuery("select gameserver from Gameserver gameserver where address = :address") .setParameter("address", remoteAddr).getSingleResult(); retval.put("detail", "Gameserver updated"); } catch (NoResultException e) { gameserver = new Gameserver(); gameserver.setAddress(remoteAddr); retval.put("detail", "Gameserver added"); } gameserver.setLastSeen(new Date()); em.persist(gameserver); return Response.ok(retval.toString()).build(); } catch (JSONException e) { LOG.log(Level.SEVERE, e.getMessage(), e); return Response.status(Status.INTERNAL_SERVER_ERROR).build(); } }
From source file:org.opencastproject.comments.events.persistence.EventCommentDatabaseServiceImpl.java
@Override public Comment updateComment(String eventId, Comment comment) throws EventCommentDatabaseException { EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); try {//from w w w .j ava2 s. com tx.begin(); CommentDto updatedComment = CommentDatabaseUtils.mergeComment(comment, em); EventCommentDto dto = getEventComment(eventId, updatedComment.getId(), em); if (dto == null) { dto = new EventCommentDto(eventId, updatedComment, securityService.getOrganization().getId()); em.persist(dto); } else { dto.setComment(updatedComment); em.merge(dto); } tx.commit(); comment = updatedComment.toComment(userDirectoryService); sendMessageUpdate(eventId); return comment; } catch (Exception e) { logger.error("Could not update or store comment: {}", ExceptionUtils.getStackTrace(e)); if (tx.isActive()) tx.rollback(); throw new EventCommentDatabaseException(e); } finally { if (em != null) em.close(); } }
From source file:org.rhq.enterprise.server.content.test.RepoManagerBeanTest.java
@Test(enabled = ENABLED) public void addRepoRelationship() throws Exception { // Setup/* w w w .j a va2 s . co m*/ EntityManager entityManager = getEntityManager(); Repo repo = new Repo("repo1"); Repo relatedRepo = new Repo("repo2"); repo = repoManager.createRepo(overlord, repo); relatedRepo = repoManager.createRepo(overlord, relatedRepo); String relationshipTypeName = "testRelationshipType"; RepoRelationshipType relationshipType = new RepoRelationshipType(relationshipTypeName); entityManager.persist(relationshipType); entityManager.flush(); // Test repoManager.addRepoRelationship(overlord, repo.getId(), relatedRepo.getId(), relationshipTypeName); // Verify RepoCriteria repoCriteria = new RepoCriteria(); repoCriteria.fetchRepoRepoGroups(true); repoCriteria.addFilterId(repo.getId()); PageList<Repo> repoPageList = repoManager.findReposByCriteria(overlord, repoCriteria); assert repoPageList.size() == 1; Repo persistedRepo = repoPageList.get(0); Set<RepoRepoRelationship> relationships = persistedRepo.getRepoRepoRelationships(); assert relationships.size() == 1; RepoRepoRelationship relationship = relationships.iterator().next(); assert relationship.getRepoRepoRelationshipPK().getRepo().getName().equals("repo1"); assert relationship.getRepoRepoRelationshipPK().getRepoRelationship().getRelatedRepo().getName() .equals("repo2"); assert relationship.getRepoRepoRelationshipPK().getRepoRelationship().getRepoRelationshipType().getName() .equals(relationshipTypeName); // Cleanup handled by rollback in tear down method }
From source file:com.sun.socialsite.userapi.UserManagerImpl.java
private UserRole getOrCreateRole(String roleName) throws PersistenceException { UserRole role = null;/*from w w w . j a v a 2 s. c o m*/ try { Query query = getNamedQuery("UserRole.findByRoleName"); query.setParameter("roleName", roleName); role = (UserRole) query.getSingleResult(); } catch (NoResultException nre) { // create the role in database EntityManager em2 = null; try { em2 = getEmf().createEntityManager(); em2.getTransaction().begin(); UserRole newRole = new UserRole(); newRole.setRoleName(roleName); em2.persist(newRole); em2.flush(); em2.getTransaction().commit(); } catch (PersistenceException pe) { if (em2 == null) { // If we couldn't even create an EntityManager, something is clearly wrong throw pe; } else { // Otherwise, ignore exception for now; the role may have been created in another thread if (em2.getTransaction().isActive()) em2.getTransaction().rollback(); } } finally { if (em2 != null) em2.close(); } } // If role is null, try again (since it _should_ now exist in the DB). if (role == null) { Query query = getNamedQuery("UserRole.findByRoleName"); query.setParameter("roleName", roleName); role = (UserRole) query.getSingleResult(); } return role; }
From source file:org.artificer.repository.hibernate.HibernatePersistenceManager.java
@Override public ArtificerOntology persistOntology(final ArtificerOntology ontology) throws ArtificerException { if (StringUtils.isBlank(ontology.getUuid())) { ontology.setUuid(UUID.randomUUID().toString()); }//from w w w . j a v a 2 s .com new HibernateUtil.HibernateTask<Void>() { @Override protected Void doExecute(EntityManager entityManager) throws Exception { // Don't trust users to properly set both sides of the association... for (ArtificerOntologyClass rootClass : ontology.getRootClasses()) { if (rootClass.getRoot() == null) { rootClass.setRoot(ontology); } } entityManager.persist(ontology); return null; } }.execute(); return ontology; }
From source file:org.opencastproject.adminui.usersettings.UserSettingsService.java
/** * Update a user setting that currently exists using its unique id to find it. * @param id The id for the user setting. * @param key The key for the user setting. * @param value The value for the user setting. * @return The updated {@link UserSetting}. * @throws UserSettingsServiceException//from w w w . j av a 2 s .c om */ public UserSetting updateUserSetting(long id, String key, String value) throws UserSettingsServiceException { EntityManager em = null; EntityTransaction tx = null; String orgId = ""; String username = ""; logger.debug("Updating user setting id: %d key: %s value: %s", id, key, value); try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); orgId = securityService.getOrganization().getId(); username = securityService.getUser().getUsername(); UserSettingDto userSettingDto = em.find(UserSettingDto.class, id); em.persist(userSettingDto); userSettingDto.setKey(key); userSettingDto.setValue(value); tx.commit(); return userSettingDto.toUserSetting(); } catch (Exception e) { logger.error("Could not update user setting username '%s' org:'%s' id:'%d' key:'%s' value:'%s':\n%s", username, orgId, id, key, value, ExceptionUtils.getStackTrace(e)); if (tx.isActive()) { tx.rollback(); } throw new UserSettingsServiceException(e); } finally { if (em != null) { em.close(); } } }
From source file:org.odk.aggregate.servlet.FormUploadServlet.java
/** * Handler for HTTP Post request that takes an xform, parses, and saves a * parsed version in the datastore /* w w w . j a va2 s.com*/ * * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); // verify user is logged in if (!verifyCredentials(req, resp)) { return; } // verify request is multipart if (!ServletFileUpload.isMultipartContent(req)) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, ErrorConsts.NO_MULTI_PART_CONTENT); return; } try { // process form MultiPartFormData uploadedFormItems = new MultiPartFormData(req); MultiPartFormItem formNameData = uploadedFormItems.getFormDataByFieldName(ServletConsts.FORM_NAME_PRAM); MultiPartFormItem formXmlData = uploadedFormItems.getFormDataByFieldName(ServletConsts.FORM_DEF_PRAM); FormParserForJavaRosa parser = null; String formName = null; String formXml = null; String xmlFileName = "default.xml"; if (formNameData != null) { formName = formNameData.getStream().toString("UTF-8"); } if (formXmlData != null) { // TODO: changed added output stream writer. probably something better exists formXml = formXmlData.getStream().toString("UTF-8"); xmlFileName = formXmlData.getFilename(); } // persist form EntityManager em = EMFactory.get().createEntityManager(); if (formName != null && formXml != null) { try { parser = new FormParserForJavaRosa(formName, user.getNickname(), formXml, xmlFileName, em); } catch (ODKFormAlreadyExistsException e) { resp.sendError(HttpServletResponse.SC_CONFLICT, ErrorConsts.FORM_WITH_ODKID_EXISTS); return; } } else { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, ErrorConsts.MISSING_FORM_INFO); return; } // TODO: do better error handling try { Form form = parser.getForm(); em.persist(form); form.printDataTree(System.out); } catch (Exception e) { e.printStackTrace(); } em.close(); resp.sendRedirect(FormsServlet.ADDR); } catch (FileUploadException e) { e.printStackTrace(resp.getWriter()); } }