List of usage examples for javax.persistence EntityManager getTransaction
public EntityTransaction getTransaction();
EntityTransaction
object. 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 w ww. j a v a2 s. c om*/ 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:in.bookmylab.jpa.JpaDAO.java
public void saveSpmBooking(SpmLabBooking spm) throws AppException { EntityManager em = emf.createEntityManager(); try {/* w ww .jav a 2 s . c o m*/ em.getTransaction().begin(); if (spm.spmId == null) { em.persist(spm); fixAnalysisModesAndResourceType(spm.booking, em, false); } else { // Validate status change, if any Query q = em.createNamedQuery("ResourceBooking.findById"); ResourceBooking rb = (ResourceBooking) q.setParameter("bookingId", spm.booking.bookingId) .getSingleResult(); if (!statusChangeValid(rb.status, spm.booking.status)) { throw new AppException(String.format("Status cannot be changed from %s to %s.", rb.status, spm.booking.status)); } fixAnalysisModesAndResourceType(spm.booking, em, true); em.merge(spm); } em.getTransaction().commit(); } finally { em.close(); } }
From source file:in.bookmylab.jpa.JpaDAO.java
public void saveXrdBooking(XrdLabBooking xrd) throws AppException { EntityManager em = emf.createEntityManager(); try {//from w w w. j a v a 2 s .c om em.getTransaction().begin(); if (xrd.xrdId == null) { em.persist(xrd); fixAnalysisModesAndResourceType(xrd.booking, em, false); } else { // Validate status change, if any Query q = em.createNamedQuery("ResourceBooking.findById"); ResourceBooking rb = (ResourceBooking) q.setParameter("bookingId", xrd.booking.bookingId) .getSingleResult(); if (!statusChangeValid(rb.status, xrd.booking.status)) { throw new AppException(String.format("Status cannot be changed from %s to %s.", rb.status, xrd.booking.status)); } fixAnalysisModesAndResourceType(xrd.booking, em, true); em.merge(xrd); } em.getTransaction().commit(); } finally { em.close(); } }
From source file:cz.fi.muni.pa165.dto.BookDAOTest.java
@Test public void testInsert() { EntityManager em = emf.createEntityManager(); BookDAOImpl bdao = new BookDAOImpl(); bdao.setManager(em);//ww w. j a v a 2s . c om Book book = new Book(); book.setAuthors("Author"); book.setDepartment(Department.Sport); book.setDescription("Description"); book.setISBN("123456456"); book.setName("Name"); em.getTransaction().begin(); bdao.insert(book); em.getTransaction().commit(); List<Book> books = em.createQuery("SELECT b FROM Book b", Book.class).getResultList(); em.close(); assertEquals(books.size(), 2); }
From source file:com.ge.apm.service.data.DataService.java
public Object postDirectData(String tablename, List<Map> list) { if (tablename == null) return "{\"code\":\"1\",\"msg\":\"please input table_name\"}"; if (list == null || list.isEmpty()) return "{\"code\":\"1\",\"msg\":\"no data post\"}"; String tableName = tablename.toLowerCase(); String talbeClassName = "com.ge.apm.domain." + tabelNameToClassName(tableName); Class<?> table = getDao(talbeClassName); Map<String, String> fields = getFields(table); EntityManagerFactory emf = WebUtil.getBean(EntityManagerFactory.class); EntityManager em = emf.createEntityManager(); int fortimes = list.size() / 50 + 1;// for (int j = 0; j < fortimes; j++) { List<Map> subList = list.subList(j * 50, (j + 1) * 50 < list.size() ? (j + 1) * 50 : list.size()); em.getTransaction().begin(); Query query = null;// ww w . j av a 2s . c o m for (int i = 0; i < subList.size(); i++) { Map<String, Object> map = subList.get(i); String outColumnStr = "insert into " + tableName + " ("; String outValueStr = ") values("; String[] strs = insertColumn(fields, map); outColumnStr += strs[0]; outValueStr += strs[1]; String sql = outColumnStr + outValueStr + ")"; query = em.createNativeQuery(sql); query.executeUpdate(); } try { em.getTransaction().commit(); } catch (Exception ex) { em.getTransaction().rollback(); Logger.getLogger(DataGetAndPushController.class.getName()).log(Level.SEVERE, null, ex); em.close(); return "{\"code\":\"1\",\"msg\":\"save failed\"}";// } } if (em != null) { em.close(); } return "{\"code\":\"0\",\"msg\":\"save success\"}";//? }
From source file:com.sixsq.slipstream.run.RunNodeResource.java
private void deleteNodeInstancesInTransaction(Representation entity) throws Exception { EntityManager em = PersistenceUtil.createEntityManager(); EntityTransaction transaction = em.getTransaction(); Run run = Run.loadFromUuid(getUuid(), em); try {//w w w . ja v a 2 s . c o m Form form = new Form(entity); boolean deleteOnly = "true".equals(form.getFirstValue(DELETE_INSTANCE_IDS_ONLY_FORM_PARAM, "").trim()) ? true : false; if (!deleteOnly) { validateRun(run); } transaction.begin(); String ids = form.getFirstValue(INSTANCE_IDS_REMOVE_FORM_PARAM, ""); if (ids.isEmpty()) { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Provide list of node instance IDs to be removed from the Run."); } else { String cloudServiceName = ""; try { cloudServiceName = run.getCloudServiceNameForNode(nodename); } catch (NullPointerException ex) { throwClientBadRequest("Invalid nodename: " + nodename); } List<String> instanceIds = Arrays.asList(ids.split("\\s*,\\s*")); for (String _id : instanceIds) { String instanceName = ""; try { instanceName = getNodeInstanceName(Integer.parseInt(_id)); } catch (NumberFormatException ex) { throwClientBadRequest("Invalid instance name: " + _id); } setRemovingNodeInstance(run, instanceName); run.removeNodeInstanceName(instanceName, cloudServiceName); } run.postEventScaleDown(nodename, instanceIds); // update instance ids removeNodeInstanceIndices(run, instanceIds); decrementNodeMultiplicityOnRun(instanceIds.size(), run); } if (!deleteOnly) { StateMachine.createStateMachine(run).tryAdvanceToProvisionning(); } transaction.commit(); } catch (Exception ex) { if (transaction.isActive()) { transaction.rollback(); } throw ex; } finally { em.close(); } getResponse().setStatus(Status.SUCCESS_NO_CONTENT); }
From source file:nl.b3p.kaartenbalie.core.server.persistence.MyEMFDatabase.java
@Override public void init(ServletConfig config) throws ServletException { super.init(config); DataMonitoring/*from w w w. ja v a2 s . co m*/ .setEnableMonitoring(getConfigValue(config, "reporting", "disabled").equalsIgnoreCase("enabled")); AccountManager .setEnableAccounting(getConfigValue(config, "accounting", "disabled").equalsIgnoreCase("enabled")); Object identity = null; try { openEntityManagerFactory(defaultKaartenbaliePU); identity = createEntityManager(MyEMFDatabase.INIT_EM); log.debug("Getting entity manager ......"); EntityManager em = getEntityManager(MyEMFDatabase.INIT_EM); EntityTransaction tx = em.getTransaction(); tx.begin(); // ReportGenerator.startupClear(em); tx.commit(); } catch (Throwable e) { log.warn("Error creating EntityManager: ", e); throw new ServletException(e); } finally { log.debug("Closing entity manager ....."); closeEntityManager(identity, MyEMFDatabase.INIT_EM); } cachePath = getConfigValue(config, "cache", "/"); if (cachePath != null) { cachePath = getServletContext().getRealPath(cachePath); log.debug("cache pad: " + cachePath); } rg = new Random(); String allowedUpload = config.getInitParameter("allowed_upload_files"); if (allowedUpload != null && allowedUpload.length() > 0) { allowedUploadFiles = allowedUpload.split(","); } // load global context params initGlobalContextParams(config); // configure kb via properties KBConfiguration.configure(); }
From source file:com.headissue.pigeon.survey.answer.AnswerSurveyTest.java
void setUpPersistence() { survey = new Survey(); survey.setName("vvk"); survey.setStatus(SurveyStatus.ENABLED); survey.setCreateAt(createDate(2012, 8, 23, 12, 33)); survey.setUpdateAt(createDate(2012, 8, 23, 12, 34)); Question q1 = new Question(); q1.setType(QuestionType.BOOL);//from www . java 2 s. co m q1.setTitle("allgemein"); q1.setText("Gefllt Ihnen die neue Suche nach Vorverkaufsstellen?"); q1.addAnswer("Ja", 1); q1.addAnswer("Nein", 2); q1.setOrderBy(1); survey.addQuestion(q1); Question q2 = new Question(); q2.setType(QuestionType.CHOICE); q2.setTitle("allgemein"); q2.setText("Bewerten Sie das Buttondesign:"); q2.addAnswer("Eins", 1); q2.addAnswer("Zwei", 2); q2.addAnswer("Drei", 3); q2.addAnswer("Vier", 4); q2.addAnswer("Fnf", 5); q2.addAnswer("Sechs", 6); q2.setOrderBy(2); survey.addQuestion(q2); Question q3 = new Question(); q3.setType(QuestionType.MULTIPLE); q3.setTitle("allgemein"); q3.setText("Kreuzen Sie Zutreffendes an."); q3.addAnswer("Ich wnsche mir mehr Optionen", 1); q3.addAnswer("Ich wnsche mir einen Share-Button", 2); q3.addAnswer("Ich wnsche mir einen Drucken-Button", 3); q3.addAnswer("Was ist das denn? Amnesiestaub! Fantastisch!", 4); q3.addAnswer("Ich bin vollends zufrieden", 5); q3.setOrderBy(3); survey.addQuestion(q3); Question q4 = new Question(); q4.setType(QuestionType.FREE); q4.setTitle("allgemein"); q4.setText("Haben Sie noch einen Verbesserungsvorschlag?"); q4.setOrderBy(4); survey.addQuestion(q4); EntityManager manager = factory.createEntityManager(); manager.getTransaction().begin(); manager.persist(survey); manager.persist(q1); manager.persist(q2); manager.persist(q3); manager.persist(q4); manager.getTransaction().commit(); //manager.close(); question1 = createValues(q1); question2 = createValues(q2); question3 = createValues(q3); question4 = createValues(q4); LogUtils.debug(log, "question 1: %s", question1); LogUtils.debug(log, "question 2: %s", question2); LogUtils.debug(log, "question 3: %s", question3); LogUtils.debug(log, "question 4: %s", question4); }
From source file:org.opencastproject.userdirectory.jpa.JpaUserAndRoleProvider.java
/** * A utility class to load the user directory. * // w w w. j a v a2 s .c o m * @param user * the user object */ public void addUser(JpaUser user) { // Create a JPA user with an encoded password. String encodedPassword = PasswordEncoder.encode(user.getPassword(), user.getUsername()); user = new JpaUser(user.getUsername(), encodedPassword, user.getOrganization(), user.getRoles()); // Then save the user EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); em.persist(user); tx.commit(); } finally { if (tx.isActive()) { tx.rollback(); } if (em != null) em.close(); } }
From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.test.CommandITCase.java
public void printMetaCats() throws Exception { System.out.println("\n\n\n"); EntityManager em = emf.createEntityManager(); try {/*from w w w. j a v a2s . co m*/ EntityTransaction et = em.getTransaction(); et.begin(); Query query = em.createQuery(new StringBuilder().append("SELECT x FROM metaCategory x").toString()); List<NewsMetaCategory> metaList = query.getResultList(); for (NewsMetaCategory temp : metaList) { System.out.println("META: " + temp.getName() + " / " + temp.getLastmodified()); } et.commit(); } finally { em.close(); } System.out.println("\n\n\n"); }