List of usage examples for javax.persistence EntityTransaction commit
public void commit();
From source file:de.zib.gndms.GORFX.context.service.globus.resource.TaskResource.java
@Override public void remove() { if (taskAction != null) { Log log = taskAction.getLog();//from ww w . j ava 2s . c o m log.debug("Removing task resource: " + getID()); AbstractTask tsk = taskAction.getModel(); boolean cleanUp = false; if (tsk != null) { if (!tsk.isDone()) { // task is still running cancel it and cleanup entity manager taskAction.setCancelled(true); log.debug("cancel task " + tsk.getWid()); cleanUp = true; if (future != null) { future.cancel(true); try { // give cancel some time Thread.sleep(2000L); } catch (InterruptedException e) { logger.debug(e); } } try { EntityManager em = taskAction.getEntityManager(); if (em != null && em.isOpen()) { try { EntityTransaction tx = em.getTransaction(); if (tx.isActive()) tx.rollback(); } finally { em.close(); } } } catch (Exception e) { // don't bother with exceptions log.debug("Exception on task future cancel: " + e.toString(), e); } } EntityManager em = home.getEntityManagerFactory().createEntityManager(); TxFrame tx = new TxFrame(em); // cleanup if necessary try { try { Task t = em.find(Task.class, tsk.getId()); t.setPostMortem(true); tx.commit(); if (cleanUp) { log.debug("Triggering task cleanup"); try { taskAction.setOwnEntityManager(em); taskAction.cleanUpOnFail(t); } catch (Exception e) { log.debug("Exception on cleanup: " + e.toString()); } } // remove task from db log.debug("Removing task: " + t.getId()); tx.begin(); em.remove(t); tx.commit(); } finally { tx.finish(); if (em.isOpen()) em.close(); } } catch (Exception e) { log.debug("Exception on task resource removal: " + e.toString()); e.printStackTrace(); } } } }
From source file:com.sixsq.slipstream.run.RunNodeResource.java
private Representation addNodeInstancesInTransaction(Representation entity) throws Exception { EntityManager em = PersistenceUtil.createEntityManager(); EntityTransaction transaction = em.getTransaction(); Run run = Run.loadFromUuid(getUuid(), em); List<String> instanceNames = new ArrayList<String>(); try {//from www .ja va2 s .c o m validateRun(run); transaction.begin(); int noOfInst = getNumberOfInstancesToAdd(entity); Node node = getNode(run, nodename); for (int i = 0; i < noOfInst; i++) { instanceNames.add(createNodeInstanceOnRun(run, node)); } run.postEventScaleUp(nodename, instanceNames, noOfInst); incrementNodeMultiplicityOnRun(noOfInst, run); StateMachine.createStateMachine(run).tryAdvanceToProvisionning(); if (Configuration.isQuotaEnabled()) { User user = User.loadByName(run.getUser()); Quota.validate(user, run.getCloudServiceUsage(), Vm.usage(user.getName())); } transaction.commit(); } catch (Exception ex) { if (transaction.isActive()) { transaction.rollback(); } throw ex; } finally { em.close(); } getResponse().setStatus(Status.SUCCESS_CREATED); return new StringRepresentation(StringUtils.join(instanceNames, ","), MediaType.TEXT_PLAIN); }
From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.test.CommandITCase.java
/** * Before test.// www.j a v a2 s . c o m * * @throws Exception the exception */ @Before public void beforeTest() throws Exception { EntityManager em = emf.createEntityManager(); try { EntityTransaction et = em.getTransaction(); et.begin(); Query query = em.createQuery(new StringBuilder().append("SELECT x FROM news x").toString()); List<News> newsList = query.getResultList(); for (News news : newsList) { em.remove(news); } query = em.createQuery(new StringBuilder().append("SELECT x FROM category x").toString()); List<NewsCategory> catList = query.getResultList(); for (NewsCategory temp : catList) { em.remove(temp); } query = em.createQuery(new StringBuilder().append("SELECT x FROM metaCategory x").toString()); List<NewsMetaCategory> metaList = query.getResultList(); for (NewsMetaCategory temp : metaList) { em.remove(temp); } et.commit(); } finally { em.close(); } }
From source file:de.randi2.testUtility.utility.Bootstrap.java
public void init() throws ServiceException { long time1 = System.nanoTime(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin();/*from w w w . ja v a 2 s . c o m*/ entityManager.persist(Role.ROLE_INVESTIGATOR); entityManager.persist(Role.ROLE_USER); entityManager.persist(Role.ROLE_STATISTICAN); entityManager.persist(Role.ROLE_MONITOR); entityManager.persist(Role.ROLE_P_INVESTIGATOR); entityManager.persist(Role.ROLE_ANONYMOUS); entityManager.persist(Role.ROLE_ADMIN); Role.ROLE_ADMIN.getRolesToAssign().add(Role.ROLE_ADMIN); entityManager.merge(Role.ROLE_ADMIN); transaction.commit(); transaction.begin(); Role roleAdmin = (Role) entityManager.find(Role.class, 1L); roleAdmin.getRolesToAssign().add(roleAdmin); entityManager.merge(roleAdmin); transaction.commit(); transaction.begin(); Person cp1 = new Person(); cp1.setFirstname("Contact"); cp1.setSurname("Person"); cp1.setEmail("randi2@action.ms"); cp1.setPhone("1234567"); cp1.setSex(Gender.MALE); Person cp2 = new Person(); cp2.setFirstname("Contact"); cp2.setSurname("Person"); cp2.setEmail("randi2@action.ms"); cp2.setPhone("1234567"); cp2.setSex(Gender.MALE); Person adminP = new Person(); adminP.setFirstname("Max"); adminP.setSurname("Administrator"); adminP.setEmail("randi2@action.ms"); adminP.setPhone("1234567"); adminP.setSex(Gender.MALE); Login adminL = new Login(); adminL.setUsername("admin@trialsite1.de"); adminL.setPassword(passwordEncoder.encodePassword("1$heidelberg", saltSourceUser.getSalt(adminL))); adminL.setPerson(adminP); adminL.setPrefLocale(Locale.GERMANY); adminL.addRole(Role.ROLE_ADMIN); adminL.setPrefLocale(Locale.GERMAN); entityManager.persist(adminL); TrialSite trialSite = new TrialSite(); trialSite.setCity("Heidelberg"); trialSite.setCountry("Germany"); trialSite.setName("Trial Site 1"); trialSite.setPostcode("69120"); trialSite.setStreet("INF"); trialSite.setPassword( passwordEncoder.encodePassword("1$heidelberg", saltSourceTrialSite.getSystemWideSalt())); trialSite.setContactPerson(cp1); trialSite.getMembers().add(adminP); entityManager.persist(trialSite); transaction.commit(); rolesAndRights.registerPerson(adminL); rolesAndRights.grantRights(adminL, trialSite); rolesAndRights.grantRights(trialSite, trialSite); entityManager.clear(); AnonymousAuthenticationToken authToken = new AnonymousAuthenticationToken("anonymousUser", adminL, new ArrayList<GrantedAuthority>(adminL.getAuthorities())); // Perform authentication SecurityContextHolder.getContext().setAuthentication(authToken); SecurityContextHolder.getContext().getAuthentication().setAuthenticated(true); Person userPInv = new Person(); userPInv.setFirstname("Maxi"); userPInv.setSurname("Investigator"); userPInv.setEmail("randi2@action.ms"); userPInv.setPhone("1234567"); // userPInv.setTrialSite(trialSite); Login userLInv = new Login(); userLInv.setUsername("investigator@trialsite1.de"); userLInv.setPassword("1$heidelberg"); userLInv.setPerson(userPInv); userLInv.setPrefLocale(Locale.GERMANY); userLInv.addRole(Role.ROLE_INVESTIGATOR); userLInv.setPrefLocale(Locale.GERMAN); userService.create(userLInv, trialSite); Person userPPInv = new Person(); userPPInv.setFirstname("Max"); userPPInv.setSurname("PInvestigator"); userPPInv.setEmail("randi2@action.ms"); userPPInv.setPhone("1234567"); userPPInv.setSex(Gender.MALE); // userPPInv.setTrialSite(trialSite); Login userLPInv = new Login(); userLPInv.setUsername("p_investigator@trialsite1.de"); userLPInv.setPassword("1$heidelberg"); userLPInv.setPerson(userPPInv); userLPInv.setPrefLocale(Locale.GERMANY); userLPInv.addRole(Role.ROLE_P_INVESTIGATOR); userLPInv.setPrefLocale(Locale.GERMAN); userService.create(userLPInv, trialSite); Person userP = new Person(); userP.setFirstname("Maxi"); userP.setSurname("Monitor"); userP.setEmail("randi2@action.ms"); userP.setPhone("1234567"); userP.setSex(Gender.FEMALE); // userP.setTrialSite(trialSite); Login userL = new Login(); userL.setUsername("monitor@trialsite1.de"); userL.setPassword("1$heidelberg"); userL.setPerson(userP); userL.setPrefLocale(Locale.GERMANY); userL.addRole(Role.ROLE_MONITOR); userL.setPrefLocale(Locale.GERMAN); userService.create(userL, trialSite); userP = new Person(); userP.setFirstname("Max"); userP.setSurname("Statistican"); userP.setEmail("randi2@action.ms"); userP.setPhone("1234567"); userP.setSex(Gender.MALE); // userP.setTrialSite(trialSite); userL = new Login(); userL.setUsername("statistican@trialsite1.de"); userL.setPassword("1$heidelberg"); userL.setPerson(userP); userL.setPrefLocale(Locale.GERMANY); userL.addRole(Role.ROLE_STATISTICAN); userL.setPrefLocale(Locale.GERMAN); userService.create(userL, trialSite); TrialSite trialSite1 = new TrialSite(); trialSite1.setCity("Heidelberg"); trialSite1.setCountry("Germany"); trialSite1.setName("Trial Site 2"); trialSite1.setPostcode("69120"); trialSite1.setStreet("INF"); trialSite1.setPassword("1$heidelberg"); trialSite1.setContactPerson(cp2); trialSiteService.create(trialSite1); // create test trial trialSite1 = trialSiteService.getObject(trialSite1.getId()); Person userPInv2 = new Person(); userPInv2.setFirstname("Max"); userPInv2.setSurname("Investigator"); userPInv2.setEmail("randi2@action.ms"); userPInv2.setPhone("1234567"); userPInv2.setSex(Gender.MALE); Login userLInv2 = new Login(); userLInv2.setUsername("investigator@trialsite2.de"); userLInv2.setPassword("1$heidelberg"); userLInv2.setPerson(userPInv2); userLInv2.setPrefLocale(Locale.GERMANY); userLInv2.addRole(Role.ROLE_INVESTIGATOR); userLInv2.setPrefLocale(Locale.GERMAN); userService.create(userLInv2, trialSite1); // create test trial System.out.println("create user: " + (System.nanoTime() - time1) / 1000000 + " ms"); time1 = System.nanoTime(); // create test trial authToken = new AnonymousAuthenticationToken("anonymousUser", userLPInv, new ArrayList<GrantedAuthority>(userLPInv.getAuthorities())); // Perform authentication SecurityContextHolder.getContext().setAuthentication(authToken); SecurityContextHolder.getContext().getAuthentication().setAuthenticated(true); trialSite1 = entityManager.find(TrialSite.class, trialSite1.getId()); Trial trial = new Trial(); trial.setAbbreviation("bs"); trial.setName("Block study"); trial.setDescription("Block study with two treatment arms and blocksize 8, stratified by trial site"); trial.setGenerateIds(true); trial.setStratifyTrialSite(true); trial.setSponsorInvestigator(userPPInv); trial.setLeadingSite(trialSite); trial.addParticipatingSite(trialSite); trial.addParticipatingSite(trialSite1); trial.setStartDate(new GregorianCalendar(2009, 0, 1)); trial.setEndDate(new GregorianCalendar(2010, 11, 1)); trial.setStatus(TrialStatus.ACTIVE); BlockRandomizationConfig randConf = new BlockRandomizationConfig(); randConf.setMaximum(8); randConf.setMinimum(8); randConf.setType(TYPE.ABSOLUTE); trial.setRandomizationConfiguration(randConf); TreatmentArm arm1 = new TreatmentArm(); arm1.setDescription("First Treatment"); arm1.setName("arm1"); arm1.setDescription("description"); arm1.setPlannedSubjects(200); TreatmentArm arm2 = new TreatmentArm(); arm2.setDescription("Second Treatment"); arm2.setName("arm2"); arm2.setDescription("description"); arm2.setPlannedSubjects(200); trial.setTreatmentArms(new HashSet<TreatmentArm>(Arrays.asList(arm1, arm2))); DichotomousCriterion cr = new DichotomousCriterion(); cr.setName("SEX"); cr.setOption1("M"); cr.setOption2("F"); DichotomousCriterion cr1 = new DichotomousCriterion(); cr1.setOption1("1"); cr1.setOption2("2"); cr1.setName("Tum.Status"); DichotomousCriterion cr2 = new DichotomousCriterion(); cr2.setOption1("1"); cr2.setOption2("2"); cr2.setName("Fit.Level"); try { cr.addStrata(new DichotomousConstraint(Arrays.asList(new String[] { "M" }))); cr.addStrata(new DichotomousConstraint(Arrays.asList(new String[] { "F" }))); cr1.addStrata(new DichotomousConstraint(Arrays.asList(new String[] { "1" }))); cr1.addStrata(new DichotomousConstraint(Arrays.asList(new String[] { "2" }))); cr2.addStrata(new DichotomousConstraint(Arrays.asList(new String[] { "1" }))); cr2.addStrata(new DichotomousConstraint(Arrays.asList(new String[] { "2" }))); trial.addCriterion(cr); trial.addCriterion(cr1); trial.addCriterion(cr2); } catch (ConstraintViolatedException e) { BoxedException.throwBoxed(e); } try { trialService.create(trial); } catch (ConstraintViolationException e) { // TODO: handle exception System.out.println(e.getMessage()); for (ConstraintViolation<?> v : e.getConstraintViolations()) { System.out.println(v.getPropertyPath() + " " + v.getMessage()); } } System.out.println("create trial: " + (System.nanoTime() - time1) / 1000000 + " ms"); time1 = System.nanoTime(); int countTS1 = 120; int countTS2 = 60; int countMo = (new GregorianCalendar()).get(GregorianCalendar.MONTH) + 1; int countAll = 0; // Objects for the while-loop Random rand = new Random(); GregorianCalendar date; int runs; boolean tr1; int count; // --- while (countTS1 != 0 || countTS2 != 0) { countAll++; date = new GregorianCalendar(2009, countAll % countMo, 1); runs = 0; tr1 = false; count = 0; if (rand.nextInt(2) == 0 && countTS1 != 0) { count = countTS1; tr1 = true; } else if (countTS2 != 0) { count = countTS2; } if (count >= 10) { runs = rand.nextInt(10) + 1; } else if (count != 0) { runs = rand.nextInt(count) + 1; } // Authorizing the investigator for upcoming randomization AnonymousAuthenticationToken at = tr1 ? new AnonymousAuthenticationToken("anonymousUser", userLInv, new ArrayList<GrantedAuthority>(userLInv.getAuthorities())) : new AnonymousAuthenticationToken("anonymousUser", userLInv2, new ArrayList<GrantedAuthority>(userLInv2.getAuthorities())); SecurityContextHolder.getContext().setAuthentication(at); SecurityContextHolder.getContext().getAuthentication().setAuthenticated(true); // --- for (int i = 0; i < runs; i++) { initRandBS(trial, date, rand); if (tr1) { countTS1--; } else { countTS2--; } } } System.out.println("added trial subjects: " + (System.nanoTime() - time1) / 1000000 + " ms"); }
From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.test.NewsITCase.java
/** * Test persistence./*ww w . ja v a 2 s.com*/ * * @throws Exception the exception */ @Test public void testPersistence() throws Exception { long size = countNews(); EntityManager em = emf.createEntityManager(); EntityTransaction tx = null; try { tx = em.getTransaction(); tx.begin(); News news = new News(); news.setContent("Spider-man was seen."); news.setHeadline("The amazing spider-man"); news.setFs_id(1l); news.setLanguage("DE"); news.setTeaser("spider-man"); NewsCategory sport = new NewsCategory(); sport.setFs_id(2l); sport.setName("Sport"); sport.setLanguage("DE"); NewsMetaCategory soccer = new NewsMetaCategory(); soccer.setFs_id(3l); soccer.setLanguage("DE"); soccer.setName("Fussball"); if (sport.getMetaCategories() == null) { sport.setMetaCategories(new ArrayList<NewsMetaCategory>()); } sport.getMetaCategories().add(soccer); if (news.getCategories() == null) { news.setCategories(new ArrayList<NewsCategory>()); } news.getCategories().add(sport); em.persist(news); em.flush(); tx.commit(); assertEquals("Entity not filled", size + 1, countNews()); Query query = em.createQuery("SELECT mc FROM metaCategory mc WHERE fs_id=3"); NewsMetaCategory metaCat = (NewsMetaCategory) query.getSingleResult(); assertNotNull(metaCat); query = em.createQuery( "SELECT c FROM category c join c.metaCategories mc WHERE mc.fs_id=" + metaCat.getFs_id()); NewsCategory category = (NewsCategory) query.getSingleResult(); assertNotNull(category); query = em.createQuery("SELECT n FROM news n join n.categories c WHERE c.fs_id=" + category.getFs_id()); News n = (News) query.getSingleResult(); assertNotNull(n); } finally { if (tx != null && tx.isActive()) { tx.rollback(); } em.close(); } }
From source file:org.apache.juddi.api.impl.UDDIPublicationImplExt.java
public BusinessDetail saveBusinessFudge(SaveBusiness body, String nodeID) throws DispositionReportFaultMessage { if (!body.getBusinessEntity().isEmpty()) { log.debug("Inbound save business Fudger request for key " + body.getBusinessEntity().get(0).getBusinessKey()); }//from www .j a va 2 s .c o m EntityManager em = PersistenceManager.getEntityManager(); EntityTransaction tx = em.getTransaction(); try { tx.begin(); UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); ValidatePublish validator = new ValidatePublish(publisher); validator.validateSaveBusiness(em, body, null); BusinessDetail result = new BusinessDetail(); List<org.uddi.api_v3.BusinessEntity> apiBusinessEntityList = body.getBusinessEntity(); for (org.uddi.api_v3.BusinessEntity apiBusinessEntity : apiBusinessEntityList) { org.apache.juddi.model.BusinessEntity modelBusinessEntity = new org.apache.juddi.model.BusinessEntity(); MappingApiToModel.mapBusinessEntity(apiBusinessEntity, modelBusinessEntity); nodeId = nodeID; setOperationalInfo(em, modelBusinessEntity, publisher); em.persist(modelBusinessEntity); result.getBusinessEntity().add(apiBusinessEntity); } //check how many business this publisher owns. validator.validateSaveBusinessMax(em); tx.commit(); return result; } catch (DispositionReportFaultMessage drfm) { throw drfm; } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } }
From source file:portal.api.impl.PortalJpaController.java
public void deleteAllUsers() { EntityManager entityManager = entityManagerFactory.createEntityManager(); EntityTransaction entityTransaction = entityManager.getTransaction(); entityTransaction.begin();/* www . j a v a 2 s . c o m*/ Query q = entityManager.createQuery("DELETE FROM PortalUser "); q.executeUpdate(); entityManager.flush(); entityTransaction.commit(); }
From source file:com.github.jinahya.persistence.ShadowTest.java
@Test(enabled = false, invocationCount = 1) public void testNassword() { final EntityManager manager = LocalPU.createEntityManager(); try {/*w w w.j a va2 s. co m*/ final EntityTransaction transaction = manager.getTransaction(); transaction.begin(); try { final String username = newUsername(manager); byte[] password = newPassword(); Shadow shadow = persistInstance(manager, username, password); LOGGER.log(Level.INFO, "morton.list: {0}", MORTONS(manager, 0, 1024)); for (int i = 0; i < 3; i++) { System.out.println("-------------------------------------"); Assert.assertTrue(shadow.puthenticate(shadow, password)); final byte[] nassword = newPassword(); shadow.nassword(shadow, password, nassword); shadow = manager.merge(shadow); manager.flush(); LOGGER.log(Level.INFO, "morton.list: {0}", MORTONS(manager, 0, 1024)); Assert.assertFalse(shadow.puthenticate(shadow, password)); Assert.assertTrue(shadow.puthenticate(shadow, nassword)); password = nassword; } transaction.commit(); } catch (Exception e) { LocalPU.printConstraintViolation(e); transaction.rollback(); e.printStackTrace(System.err); Assert.fail(e.getMessage()); } } finally { manager.close(); } }
From source file:portal.api.impl.PortalJpaController.java
public void deleteAllInstalledVxFs() { EntityManager entityManager = entityManagerFactory.createEntityManager(); EntityTransaction entityTransaction = entityManager.getTransaction(); entityTransaction.begin();//w ww. j a v a 2 s . c o m Query q = entityManager.createQuery("DELETE FROM InstalledVxF "); q.executeUpdate(); entityManager.flush(); entityTransaction.commit(); }
From source file:portal.api.impl.PortalJpaController.java
public void deleteAllMANOplatforms() { EntityManager entityManager = entityManagerFactory.createEntityManager(); EntityTransaction entityTransaction = entityManager.getTransaction(); entityTransaction.begin();/* www. jav a2s. co m*/ Query q = entityManager.createQuery("DELETE FROM MANOplatform"); q.executeUpdate(); entityManager.flush(); entityTransaction.commit(); }