/** * トランザクションをコミットまたはロールバックします。 * * <p>現在のスレッドに関連づけられているトランザクションがアクティブな場合は、 トランザクションをコミットします。 それ以外の場合はトランザクションをロールバックします。 * * @throws Exception トランザクションマネージャで例外が発生した場合にスローされます * @see javax.transaction.TransactionManager#commit() * @see javax.transaction.TransactionManager#rollback() */ protected void end() throws Exception { if (userTransaction.getStatus() == STATUS_ACTIVE) { userTransaction.commit(); } else { userTransaction.rollback(); } }
@Test(expected = EntityNotFoundException.class) @OperateOnDeployment(value = UtilTestClass.PRODUCTION_DEPLOYMENT) public void testRemoveBank() throws Exception { Bank bank; try { utx.begin(); bank = getBankDAO().createBank("bank", "site"); } finally { utx.commit(); } if (bank == null) { Assert.fail("Bank shouldn't be NULL"); } BigInteger bankID = bank.getID(); try { utx.begin(); try { Bank foundBank = getBankDAO().findBank(bankID); Assert.assertNotNull(foundBank); } catch (EntityNotFoundException e) { Assert.fail("Created bank is not found"); } getBankDAO().removeBank(bank); getBankDAO().findBank(bankID); } finally { utx.commit(); } }
public void destroy(BitacoraId id) throws NonexistentEntityException, RollbackFailureException, Exception { EntityManager em = null; try { utx.begin(); em = getEntityManager(); Bitacora bitacora; try { bitacora = em.getReference(Bitacora.class, id); bitacora.getId(); } catch (EntityNotFoundException enfe) { throw new NonexistentEntityException( "The bitacora with id " + id + " no longer exists.", enfe); } em.remove(bitacora); utx.commit(); } catch (Exception ex) { try { utx.rollback(); } catch (Exception re) { throw new RollbackFailureException( "An error occurred attempting to roll back the transaction.", re); } throw ex; } finally { if (em != null) { em.close(); } } }
public String guardarCargaFamiliar(GthCargasFamiliares carga) { EntityManager manejador = fabrica.createEntityManager(); try { utx.begin(); manejador.joinTransaction(); // Guarda o modifica if (carga.getIdeGtcaf() == null) { long idegtcaf = new Long(utilitario.getConexion().getMaximo("GTH_CARGAS_FAMILIARES", "IDE_GTCAF", 1)); Integer conertideaspvh = (int) idegtcaf; carga.setIdeGtcaf(conertideaspvh); manejador.persist(carga); } else { manejador.merge(carga); } utx.commit(); } catch (Exception e) { try { utx.rollback(); } catch (Exception e1) { } return e.getMessage(); } finally { manejador.close(); } return ""; }
public String guardarTelefono(GthTelefono telefono) { EntityManager manejador = fabrica.createEntityManager(); try { utx.begin(); if (telefono.getIdeGttel() == null) { // asignar maximo long ideaspvh = new Long(utilitario.getConexion().getMaximo("GTH_TELEFONO", "IDE_GTTEL", 1)); System.out.println("guardar telefono " + ideaspvh); Integer conertideaspvh = 1; // (int) ideaspvh; telefono.setIdeGttel(conertideaspvh); // maximo de utilitario System.out.println("telefono " + telefono); manejador.persist(telefono); } else { manejador.merge(telefono); } utx.commit(); } catch (Exception e) { try { utx.rollback(); } catch (Exception e1) { } return e.getMessage(); } finally { manejador.close(); } return ""; }
@Override public SessionDto login(String username, String attemptedPassword) { log.debug("logging in user: "******"Could not log in!", e); throw new RuntimeException("Could not log in!"); } }
public void deletePPE(int w, int d, String t) { FacesMessage msg; Pruefplaneintrag ppe = pkh.findPPEByTimeAndDay(w, d, t); Pruefperioden currenPruefperiode = ppe.getPruefPeriode(); int ppeId = ppe.getPpid(); Logger.getLogger(PruefplaneintragHandler.class.getName()) .log(Level.INFO, "Start deletePPE, selected: {0}", ppeId); try { utx.begin(); em.remove(em.merge(ppe)); utx.commit(); this.updateStatus(ppe, new ArrayList<Pruefplaneintrag>()); Logger.getLogger(PruefplaneintragHandler.class.getName()) .log(Level.INFO, "Success at deletePPE, deleted: {0}", ppe.getPpid()); msg = new FacesMessage( FacesMessage.SEVERITY_INFO, "Prüfung gelöscht: ", ppe.getSgmid().getModID().getModName()); FacesContext.getCurrentInstance().addMessage(null, msg); allPpe = this.findAllPPE(); pkh.updateWeek(currenPruefperiode.getPPWoche()); } catch (Exception ex) { Logger.getLogger(PruefplaneintragHandler.class.getName()).log(Level.SEVERE, null, ex); } }
@Test(expected = EntityNotFoundException.class) @OperateOnDeployment(value = UtilTestClass.PRODUCTION_DEPLOYMENT) public void testRemoveUser() throws Exception { User user; try { utx.begin(); user = getUserDAO().createUser("name", "name", "name", "nick", "password"); } finally { utx.commit(); } if (user == null) { Assert.fail("User shouldn't be NULL"); } BigInteger userID = user.getID(); try { utx.begin(); try { User foundUser = getUserDAO().findUser(userID); Assert.assertNotNull(foundUser); } catch (EntityNotFoundException e) { Assert.fail("Created user is not found"); } getUserDAO().removeUser(user); getUserDAO().findUser(userID); } finally { utx.commit(); } }
@Test @InSequence(2) @Ignore public void testTransactionCommit() throws Throwable { userTx.begin(); HazelcastConnection c = getConnection(); try { TransactionalMap<String, String> m = c.getTransactionalMap("testTransactionCommit"); m.put("key", "value"); doSql(); assertEquals("value", m.get("key")); } finally { c.close(); } userTx.commit(); HazelcastConnection con2 = getConnection(); try { assertEquals("value", con2.getMap("testTransactionCommit").get("key")); validateSQLdata(true); } finally { con2.close(); } }
@Test public void uowManagerAndUserTransactionFoundInJndi() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()) .willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); MockUOWManager manager = new MockUOWManager(); ExpectedLookupTemplate jndiTemplate = new ExpectedLookupTemplate(); jndiTemplate.addObject(WebSphereUowTransactionManager.DEFAULT_USER_TRANSACTION_NAME, ut); jndiTemplate.addObject(WebSphereUowTransactionManager.DEFAULT_UOW_MANAGER_NAME, manager); WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager(); ptm.setJndiTemplate(jndiTemplate); ptm.afterPropertiesSet(); DefaultTransactionDefinition definition = new DefaultTransactionDefinition(); TransactionStatus ts = ptm.getTransaction(definition); ptm.commit(ts); assertEquals( "result", ptm.execute( definition, new TransactionCallback<String>() { @Override public String doInTransaction(TransactionStatus status) { return "result"; } })); assertEquals(UOWManager.UOW_TYPE_GLOBAL_TRANSACTION, manager.getUOWType()); assertFalse(manager.getJoined()); assertFalse(manager.getRollbackOnly()); verify(ut).begin(); verify(ut).commit(); }
@Test public void testCMTInTxTimeout() throws InterruptedException, NamingException, SystemException, NotSupportedException, RollbackException, HeuristicRollbackException, HeuristicMixedException { /* Stateful test Bean. */ UserTransaction userTransaction = (UserTransaction) new InitialContext().lookup("javax.transaction.UserTransaction"); ITimeoutBean simpleTimeoutBean = (ITimeoutBean) new InitialContext().lookup("simpleTimeoutBean"); userTransaction.begin(); simpleTimeoutBean.init(); Thread.sleep(200); // Initially it should return a NoSuchEJBException immediately after the lookup but there is a // running transaction simpleTimeoutBean.ping(); userTransaction.commit(); // Now transaction is committed Thread.sleep(100); try { simpleTimeoutBean.ping(); } catch (NoSuchEJBException e) { // Should return a NoSuchEJBException immediately after the end of the transaction return; } Assert.fail("Timeout exceeded and call to the EJB doesn't throw a NoSuchEJBException"); }
@Override public int doStartTag() throws JspException { String context = ""; try { System.out.println("jsp tag start..."); ut.begin(); JMSProducer producer = jmsContext.createProducer(); TextMessage msg = jmsContext.createTextMessage("Hello JSP Tag"); producer.send(queue, msg); context = jmsContext.toString(); ut.commit(); if (context.indexOf(transactionScope) == -1) { throw new JspException("NOT in transaction scope!"); } // Get the writer object for output. JspWriter out = pageContext.getOut(); // Perform substr operation on string. out.println(text); } catch (Exception e) { throw new JspException(e); } return SKIP_BODY; }
// public static void main(String[] args) public void create() { try { Session session = HibernateUtility.getSession(); Context ctx = new InitialContext(); UserTransaction tx = (UserTransaction) ctx.lookup("java:comp/UserTransaction"); tx.begin(); // Transaction tx=session.beginTransaction(); EmployeePojo emp1 = new EmployeePojo(); emp1.setEmpid(102); emp1.setName("shamu"); emp1.setSalary(1500); session.save(emp1); EmployeePojo emp11 = new EmployeePojo(); emp11.setEmpid(103); emp11.setName("nama"); emp11.setSalary(2500); session.save(emp11); emp11.setSalary(6000); session.flush(); tx.commit(); // tx.commit(); session.close(); } catch (Exception e) { e.printStackTrace(); } }
/** * @param storeValue * @param rootPath * @param context * @param nodeService * @param searchService * @param namespaceService * @param tenantService * @param m_transactionService */ private void initializeRootNode( String storeValue, String rootPath, WebApplicationContext context, NodeService nodeService, SearchService searchService, NamespaceService namespaceService, TenantService tenantService, TransactionService m_transactionService) { // Use the system user as the authenticated context for the filesystem initialization AuthenticationContext authComponent = (AuthenticationContext) context.getBean("authenticationContext"); authComponent.setSystemUserAsCurrentUser(); // Wrap the initialization in a transaction UserTransaction tx = m_transactionService.getUserTransaction(true); try { // Start the transaction if (tx != null) tx.begin(); StoreRef storeRef = new StoreRef(storeValue); if (nodeService.exists(storeRef) == false) { throw new RuntimeException("No store for path: " + storeRef); } NodeRef storeRootNodeRef = nodeService.getRootNode(storeRef); List<NodeRef> nodeRefs = searchService.selectNodes(storeRootNodeRef, rootPath, null, namespaceService, false); if (nodeRefs.size() > 1) { throw new RuntimeException( "Multiple possible children for : \n" + " path: " + rootPath + "\n" + " results: " + nodeRefs); } else if (nodeRefs.size() == 0) { throw new RuntimeException("Node is not found for : \n" + " root path: " + rootPath); } defaultRootNode = nodeRefs.get(0); // Commit the transaction if (tx != null) tx.commit(); } catch (Exception ex) { logger.error(ex); } finally { // Clear the current system user authComponent.clearCurrentSecurityContext(); } }
public void destroy(String id) throws NonexistentEntityException, RollbackFailureException, Exception { EntityManager em = null; try { utx.begin(); em = getEntityManager(); TipoComparacion tipoComparacion; try { tipoComparacion = em.getReference(TipoComparacion.class, id); tipoComparacion.getIdComparador(); } catch (EntityNotFoundException enfe) { throw new NonexistentEntityException( "The tipoComparacion with id " + id + " no longer exists.", enfe); } em.remove(tipoComparacion); utx.commit(); } catch (Exception ex) { try { utx.rollback(); } catch (Exception re) { throw new RollbackFailureException( "An error occurred attempting to roll back the transaction.", re); } throw ex; } finally { if (em != null) { em.close(); } } }
@Test(expected = EntityNotFoundException.class) @OperateOnDeployment(value = UtilTestClass.PRODUCTION_DEPLOYMENT) public void testRemoveDocumentTemplate() throws Exception { DocumentTemplate documentTemplate; try { utx.begin(); documentTemplate = getDocumentsOfficesDAO().createDocumentTemplate("name", "%s", "%d", "officeTypeName"); } finally { utx.commit(); } if (documentTemplate == null) { Assert.fail("Document template shouldn't be NULL"); } BigInteger documentTemplateID = documentTemplate.getID(); try { utx.begin(); try { DocumentTemplate foundDocumentTemplate = getDocumentsOfficesDAO().findDocumentTemplate(documentTemplate.getID()); Assert.assertNotNull(foundDocumentTemplate); } catch (EntityNotFoundException e) { Assert.fail("Created document template is not found"); } getDocumentsOfficesDAO().removeDocumentTemplate(documentTemplate); getDocumentsOfficesDAO().findDocumentTemplate(documentTemplateID); } finally { utx.commit(); } }
private void testStartProcess(RuntimeEngine runtime) throws Exception { synchronized ( (SingleSessionCommandService) ((CommandBasedStatefulKnowledgeSession) runtime.getKieSession()).getRunner()) { UserTransaction ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction"); try { ut.begin(); logger.debug("Starting process on ksession {}", runtime.getKieSession().getIdentifier()); Map<String, Object> params = new HashMap<String, Object>(); DateTime now = new DateTime(); now.plus(1000); params.put("x", "R2/" + wait + "/PT1S"); ProcessInstance processInstance = runtime.getKieSession().startProcess("IntermediateCatchEvent", params); logger.debug( "Started process instance {} on ksession {}", processInstance.getId(), runtime.getKieSession().getIdentifier()); ut.commit(); } catch (Exception ex) { ut.rollback(); throw ex; } } }
@Test(expected = EntityNotFoundException.class) @OperateOnDeployment(value = UtilTestClass.PRODUCTION_DEPLOYMENT) public void testRemoveEmail() throws Exception { Email email; try { utx.begin(); User owner = getUserDAO().createUser("name", "name", "not name", "nick", "without password"); email = getUserDAO().createUserEmail("address", owner); } finally { utx.commit(); } if (email == null) { Assert.fail("Email shouldn't be NULL"); } BigInteger emailID = email.getID(); try { utx.begin(); try { Email foundEmail = getUserDAO().findEmail(emailID); Assert.assertNotNull(foundEmail); } catch (EntityNotFoundException e) { Assert.fail("Created email is not found"); } getUserDAO().removeUserEmail(email); getUserDAO().findEmail(emailID); } finally { utx.commit(); } }
public String guardarConducta(EquivalenciaConducta iconducta) { EquivalenciaConducta conducta = iconducta; try { utx.begin(); manejador.joinTransaction(); // nombre tabla y atributo if (conducta.getEqcCodigo() == null) { long lon_codigo = utilitario.getConexion().getMaximo("Equivalencia_conducta", "eqc_codigo", 1); conducta.setEqcCodigo(new Integer(String.valueOf(lon_codigo))); System.out.println("ide " + lon_codigo); conducta.setEqcCodigo(new Integer(String.valueOf(lon_codigo))); manejador.persist(conducta); } else { manejador.merge(conducta); } utx.commit(); } catch (Exception e) { try { utx.rollback(); } catch (Exception e1) { } e.printStackTrace(); return e.getMessage(); } return ""; }
@Override public SessionDto register(String username, String password, String name, String email) { log.debug("registering new user: "******"Could not register user!", e); throw new RuntimeException("Could not register user!"); } }
public void create(Bitacora bitacora) throws PreexistingEntityException, RollbackFailureException, Exception { if (bitacora.getId() == null) { bitacora.setId(new BitacoraId()); } EntityManager em = null; try { utx.begin(); em = getEntityManager(); em.persist(bitacora); utx.commit(); } catch (Exception ex) { try { utx.rollback(); } catch (Exception re) { throw new RollbackFailureException( "An error occurred attempting to roll back the transaction.", re); } if (findBitacora(bitacora.getId()) != null) { throw new PreexistingEntityException("Bitacora " + bitacora + " already exists.", ex); } throw ex; } finally { if (em != null) { em.close(); } } }
@Override public void updateComment(Comment comment) throws NonExistingEntityException, IllegalArgumentException { if (comment == null) { throw new IllegalArgumentException("Comment is null."); } if (comment.getId() == null) { throw new IllegalArgumentException("Comment id is null."); } commentCache = provider.getCacheContainer().getCache("commentcache"); if (!commentCache.containsKey(comment.getId())) { throw new NonExistingEntityException("Comment does not exist in cache."); } try { userTransaction.begin(); commentCache.put(comment.getId(), comment); userTransaction.commit(); logger.info("Comment with id: " + comment.getId() + " was updated in cache store."); } catch (Exception e) { if (userTransaction != null) { try { userTransaction.rollback(); } catch (Exception e1) { e1.printStackTrace(); } } logger.error("Error while updating comment.", e); throw new CacheException(e); } }
public void edit(Bitacora bitacora) throws NonexistentEntityException, RollbackFailureException, Exception { EntityManager em = null; try { utx.begin(); em = getEntityManager(); bitacora = em.merge(bitacora); utx.commit(); } catch (Exception ex) { try { utx.rollback(); } catch (Exception re) { throw new RollbackFailureException( "An error occurred attempting to roll back the transaction.", re); } String msg = ex.getLocalizedMessage(); if (msg == null || msg.length() == 0) { BitacoraId id = bitacora.getId(); if (findBitacora(id) == null) { throw new NonexistentEntityException("The bitacora with id " + id + " no longer exists."); } } throw ex; } finally { if (em != null) { em.close(); } } }
public String guardarDireccion(GthDireccion direccion) { EntityManager manejador = fabrica.createEntityManager(); try { utx.begin(); manejador.joinTransaction(); // Guarda o modifica direccion if (direccion.getIdeGtdir() == null) { long idegtdir = new Long(utilitario.getConexion().getMaximo("GTH_DIRECCION", "IDE_GTDIR", 1)); Integer conertideaspvh = (int) idegtdir; direccion.setIdeGtdir(conertideaspvh); // maximo de utilitario manejador.persist(direccion); } else { manejador.merge(direccion); } utx.commit(); } catch (Exception e) { try { utx.rollback(); } catch (Exception e1) { } return e.getMessage(); } finally { manejador.close(); } return ""; }
@Test(expected = EntityNotFoundException.class) @OperateOnDeployment(value = UtilTestClass.PRODUCTION_DEPLOYMENT) public void testRemoveOfficeType() throws Exception { GovernmentOfficeType officeType; try { utx.begin(); officeType = getDocumentsOfficesDAO().createRootOfficeType("name"); } finally { utx.commit(); } if (officeType == null) { Assert.fail("Office type shouldn't be NULL"); } BigInteger officeTypeID = officeType.getID(); try { utx.begin(); try { GovernmentOfficeType foundOfficeType = getDocumentsOfficesDAO().findOfficeType(officeType.getID()); Assert.assertNotNull(foundOfficeType); } catch (EntityNotFoundException e) { Assert.fail("Created office type is not found"); } getDocumentsOfficesDAO().removeOfficeType(officeType); getDocumentsOfficesDAO().findOfficeType(officeTypeID); } finally { utx.commit(); } }
private void saveDomainEntityToRepositoryWithTransaction(Car domainEntity) throws NotSupportedException, SystemException, RollbackException, HeuristicMixedException, HeuristicRollbackException { userTransaction.begin(); carRepository.save(domainEntity); userTransaction.commit(); }
public void edit(TipoComparacion tipoComparacion) throws NonexistentEntityException, RollbackFailureException, Exception { EntityManager em = null; try { utx.begin(); em = getEntityManager(); tipoComparacion = em.merge(tipoComparacion); utx.commit(); } catch (Exception ex) { try { utx.rollback(); } catch (Exception re) { throw new RollbackFailureException( "An error occurred attempting to roll back the transaction.", re); } String msg = ex.getLocalizedMessage(); if (msg == null || msg.length() == 0) { String id = tipoComparacion.getIdComparador(); if (findTipoComparacion(id) == null) { throw new NonexistentEntityException( "The tipoComparacion with id " + id + " no longer exists."); } } throw ex; } finally { if (em != null) { em.close(); } } }
public void testNewSessionDispose() throws Exception { KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add(ResourceFactory.newClassPathResource("sample.bpmn"), ResourceType.BPMN2); KnowledgeBase kbase = kbuilder.newKnowledgeBase(); SessionManagerFactory factory = new NewSessionSessionManagerFactory(kbase); final SessionManager sessionManager = factory.getSessionManager(); UserTransaction ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction"); ut.begin(); sessionManager.getKnowledgeSession().startProcess("com.sample.bpmn.hello", null); TransactionManagerServices.getTransactionManager() .getTransaction() .registerSynchronization( new Synchronization() { public void beforeCompletion() {} public void afterCompletion(int status) { try { sessionManager.dispose(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); ut.commit(); factory.dispose(); }
private void testStartProcess(SessionManagerFactory factory) throws Exception { SessionManager sessionManager = factory.getSessionManager(); long taskId; synchronized ( (SingleSessionCommandService) ((CommandBasedStatefulKnowledgeSession) sessionManager.getKnowledgeSession()) .getCommandService()) { UserTransaction ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction"); ut.begin(); System.out.println( "Starting process on ksession " + sessionManager.getKnowledgeSession().getId()); ProcessInstance processInstance = sessionManager.getKnowledgeSession().startProcess("com.sample.bpmn.hello", null); System.out.println( "Started process instance " + processInstance.getId() + " on ksession " + sessionManager.getKnowledgeSession().getId()); long workItemId = ((HumanTaskNodeInstance) ((WorkflowProcessInstance) processInstance).getNodeInstances().iterator().next()) .getWorkItemId(); taskId = sessionManager.getTaskService().getTaskByWorkItemId(workItemId).getId(); System.out.println("Created task " + taskId); ut.commit(); } sessionManager.getTaskService().claim(taskId, "mary"); sessionManager.dispose(); }
public String eliminarConyugue(String ideGtemp) { EntityManager manejador = fabrica.createEntityManager(); try { GthConyuge conygue = getConyuque(ideGtemp); if (conygue != null) { utx.begin(); manejador.joinTransaction(); // Borra telefono de conyugue List<GthTelefono> telefonos = getListaTelefonoConyugue(conygue.getIdeGtcon().toString()); if (telefonos != null && !telefonos.isEmpty()) { for (GthTelefono telefonoActual : telefonos) { manejador.remove(telefonoActual); } } // Borra datos de union GthUnionLibre union = getUnionLibre(conygue.getIdeGtcon().toString()); if (union != null) { manejador.remove(union); } manejador.remove(conygue); utx.commit(); } } catch (Exception e) { try { utx.rollback(); } catch (Exception e1) { } return e.getMessage(); } finally { manejador.close(); } return ""; }