/** * トランザクションをコミットまたはロールバックします。 * * <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 public void testIsActive_3() throws Exception { expect(tx.getStatus()).andThrow(new SystemException("bad")); replay(tx); try { jut.isActive(); } catch (DoceException e) { assertEquals("bad", e.getCause().getMessage()); } }
@Test public void testCommit_3() throws Exception { expect(tx.getStatus()).andReturn(Status.STATUS_ACTIVE); tx.commit(); expectLastCall().andThrow(new SystemException("bad")); replay(tx); try { jut.commit(); } catch (DoceException e) { assertEquals("bad", e.getCause().getMessage()); } }
private void beginTrx() { try { UserTransaction trx = userTransactionProvider.get(); String trxStatus = ""; if (trx.getStatus() == Status.STATUS_NO_TRANSACTION) { trx.begin(); } EntityManager em = emProvider.get(); em.joinTransaction(); trxStatus = trx.getStatus() + "; em = " + em + "[Open=" + em.isOpen() // +", joinedToTrx="+em.isJoinedToTransaction()+"]" + "; UserTrx=" + trx; log.debug(": Executing beginTrx ; TrxStatus " + trxStatus); } catch (Exception e) { e.printStackTrace(); } }
/** * Get the stored MD4 hashed password for the user, or null if the user does not exist * * @param userName String * @return MD4 hash or null */ protected String getMD4Hash(String userName) { String md4hash = null; // Wrap the auth component calls in a transaction UserTransaction tx = transactionService.getUserTransaction(); try { tx.begin(); // Get the stored MD4 hashed password for the user, or null if the user does not exist md4hash = nltmAuthenticator.getMD4HashedPassword(userName); } catch (Throwable ex) { if (getLogger().isDebugEnabled()) getLogger().debug(ex); } finally { // Rollback/commit the transaction if still valid if (tx != null) { try { // Commit or rollback the transaction if (tx.getStatus() == Status.STATUS_MARKED_ROLLBACK || tx.getStatus() == Status.STATUS_ROLLEDBACK || tx.getStatus() == Status.STATUS_ROLLING_BACK) { // Transaction is marked for rollback tx.rollback(); } else { // Commit the transaction tx.commit(); } } catch (Throwable ex) { if (getLogger().isDebugEnabled()) getLogger().debug(ex); } } } return md4hash; }
@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(); }
@Override public TransactionStatus getStatus() { try { return StatusTranslator.translate(userTransaction.getStatus()); } catch (SystemException e) { throw new TransactionException("JTA TransactionManager#getStatus failed", e); } }
public static boolean isActive(UserTransaction ut) { try { int status = ut.getStatus(); return isActive(status); } catch (SystemException error) { throw new RuntimeException(error); } }
@TransactionAttribute(TransactionAttributeType.SUPPORTS) public int transactionStatus() { try { return userTransaction.getStatus(); } catch (SystemException e) { throw new RuntimeException(e); } }
@Test public void testRollback() throws Exception { expect(tx.getStatus()).andReturn(Status.STATUS_ACTIVE); tx.rollback(); expectLastCall(); replay(tx); jut.rollback(); }
public boolean getRollbackOnly() throws IllegalStateException { try { UserTransaction userTransaction = getUserTransaction(); return (userTransaction.getStatus() == Status.STATUS_MARKED_ROLLBACK); } catch (SystemException e) { throw new KernelRuntimeException(e); } }
public void setRollbackOnly() { try { if (userTransaction.getStatus() == STATUS_ACTIVE) { userTransaction.setRollbackOnly(); } } catch (final Exception e) { logger.log("ESSR0017", new Object[] {e.getMessage()}, e); } }
public String updateKeyValueDatabase(String key, String value) { EntityManager entityManager = entityManagerFactory.createEntityManager(); try { userTransaction.begin(); /* * Since the Entity Manager (EM) is not managed by the container the developer must explicitly tell the EM * to join the transaction. Compare this with ManagedComponent where the container automatically * enlists the EM with the transaction. The persistence context managed by the EM will then be scoped * to the JTA transaction which means that all entities will be detached when the transaction commits. */ entityManager.joinTransaction(); // make some transactional changes String result = updateKeyValueDatabase(entityManager, key, value); /* * Note that the default scope of entities managed by the EM is transaction. Thus once the transaction * commits the entity will be detached from the EM. See also the comment in the finally block below. */ userTransaction.commit(); return result; } catch (RollbackException e) { // We tried to commit the transaction but it has already been rolled back (adding duplicate // keys would // generate this condition although the example does check for duplicates). Throwable t = e.getCause(); return t != null ? t.getMessage() : e.getMessage(); } catch (Exception e) { /* * An application cannot handle any of the other exceptions raised by begin and commit so we just * catch the generic exception. The meaning of the other exceptions is: * * NotSupportedException - the thread is already associated with a transaction * HeuristicRollbackException - should not happen since the example is interacting with a single database * HeuristicMixedException - should not happen since the example is interacting with a single database * SystemException - the TM raised an unexpected error. There is no standard way of handling this error * (another reason why CMT are preferable to managing them ourselves) */ return e.getMessage(); } finally { /* * Since the EM is transaction scoped it will not detach its objects even when calling close on it * until the transaction completes. Therefore we must roll back any active transaction before returning. */ try { if (userTransaction.getStatus() == Status.STATUS_ACTIVE) userTransaction.rollback(); } catch (Throwable e) { // ignore } entityManager.close(); } }
private void commitTransaction() throws Exception { UserTransaction tx = null; try { tx = getTransaction(); if (tx.getStatus() == Status.STATUS_ACTIVE) { tx.commit(); log.info("Committed transaction: " + tx); } } catch (Exception e) { log.error(e); throw e; } }
private void rollbackTxIfNeeded() { try { switch (ut.getStatus()) { case Status.STATUS_COMMITTED: case Status.STATUS_NO_TRANSACTION: break; default: ut.rollback(); } } catch (RuntimeException e) { throw e; } // SecurityException, SystemException catch (Exception e) { throw new RuntimeException(e); } }
private void commitTrx() { EntityManager em = emProvider.get(); UserTransaction trx = userTransactionProvider.get(); try { String trxStatus = userTransactionProvider.get().getStatus() + "; em = " + emProvider.get() + "; UserTrx=" + userTransactionProvider.get(); log.debug(": Executing Commit doFilterTrx - ; TrxStatus " + trxStatus); // if(entityManagers.get()!=null) int status = trx.getStatus(); /* * STATUS_ACTIVE 0 STATUS_COMMITTED 3 STATUS_COMMITTING 8 * STATUS_MARKED_ROLLBACK 1 STATUS_NO_TRANSACTION 6 STATUS_PREPARED * 2 STATUS_PREPARING 7 STATUS_ROLLEDBACK 4 STATUS_ROLLING_BACK 9 * STATUS_UNKNOWN 5 */ // JBPM engine marks transactions for rollback everytime // something goes wrong - it does'nt necessarily throw an exception if (status == 1 || status == 4 || status == 9) { log.warn("Rolling Back Trx with status " + status); trx.rollback(); } else { log.debug("Commiting Back Trx with status " + status); trx.commit(); } } catch (SecurityException | IllegalStateException | RollbackException | HeuristicMixedException | HeuristicRollbackException | SystemException e) { e.printStackTrace(); } }
/** * This method opens a new transaction, if none is currently running, and joins the entity * manager/persistence context to that transaction. * * @param em The entity manager we're using. * @return {@link UserTransaction} If we've started a new transaction, then we return it so that * it can be closed. * @throws NotSupportedException * @throws SystemException * @throws Exception if something goes wrong. */ private Object joinTransaction(EntityManager em) { boolean newTx = false; UserTransaction ut = null; if (isJTA) { try { em.joinTransaction(); } catch (TransactionRequiredException e) { ut = findUserTransaction(); try { if (ut != null && ut.getStatus() == Status.STATUS_NO_TRANSACTION) { ut.begin(); newTx = true; // since new transaction was started em must join it em.joinTransaction(); } } catch (Exception ex) { throw new IllegalStateException( "Unable to find or open a transaction: " + ex.getMessage(), ex); } if (!newTx) { // rethrow TransactionRequiredException if UserTransaction was not found or started throw e; } } if (newTx) { return ut; } } // else { // EntityTransaction tx = em.getTransaction(); // if( ! tx.isActive() ) { // tx.begin(); // return tx; // } // } return null; }
public String execute() { String rtnVal = SUCCESS; UserTransaction tx = null; try { sampleName = sampleName != null && sampleName.equals("0") ? null : sampleName; if (jobType != null) { boolean isProjectRegistration = eventName.equals(Constants.EVENT_PROJECT_REGISTRATION); boolean isSampleRegistration = eventName.equals(Constants.EVENT_SAMPLE_REGISTRATION); if (projectName == null || projectName.equals("0") || eventName == null || eventName.equals("0")) throw new Exception("Project or Event type is not selected."); if (jobType.equals("insert")) { // loads single event tx = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction"); tx.begin(); psewt.loadAll( null, this.createMultiLoadParameter(projectName, loadingProject, loadingSample, beanList)); this.reset(); } else if (jobType.equals("grid")) { // loads multiple events from grid view tx = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction"); tx.begin(); for (GridBean gBean : gridList) { if (gBean != null) { if (isProjectRegistration && gBean.getProjectName() != null && gBean.getProjectPublic() != null) { loadingProject = new Project(); loadingProject.setProjectName(gBean.getProjectName()); loadingProject.setIsPublic(Integer.valueOf(gBean.getProjectPublic())); } else if (isSampleRegistration && gBean.getSampleName() != null && gBean.getSamplePublic() != null) { loadingSample = new Sample(); loadingSample.setSampleName(gBean.getSampleName()); loadingSample.setParentSampleName(gBean.getParentSampleName()); loadingSample.setIsPublic(Integer.valueOf(gBean.getSamplePublic())); } else { if (gBean.getSampleName() != null) { this.sampleName = gBean.getSampleName(); } } List<FileReadAttributeBean> fBeanList = gBean.getBeanList(); if (fBeanList != null && fBeanList.size() > 0) { psewt.loadAll( null, this.createMultiLoadParameter( projectName, loadingProject, loadingSample, fBeanList)); } } } this.reset(); } else if (jobType.equals("file")) { // loads data from a CSV file to grid view if (!this.uploadFile.canRead()) { throw new Exception("Error in reading the file."); } else { try { CSVReader reader = new CSVReader(new FileReader(this.uploadFile)); int lineCount = 0; List<String> columns = new ArrayList<String>(); String currProjectName = null; gridList = new ArrayList<GridBean>(); boolean hasSampleName = false; String[] line; while ((line = reader.readNext()) != null) { if (lineCount != 1) { if (lineCount == 0) { Collections.addAll(columns, line); hasSampleName = columns.indexOf("SampleName") >= 0; } else { int colIndex = 0; currProjectName = line[colIndex++]; if (!isProjectRegistration && !currProjectName.equals(this.projectName)) { throw new Exception(MULTIPLE_SUBJECT_IN_FILE_MESSAGE); } GridBean gBean = new GridBean(); gBean.setProjectName(currProjectName); if (hasSampleName) { gBean.setSampleName(line[(colIndex++)]); } if (isProjectRegistration) { gBean.setProjectName(currProjectName); gBean.setProjectPublic(line[(colIndex++)]); } else if (isSampleRegistration) { gBean.setParentSampleName(line[(colIndex++)]); gBean.setSamplePublic(line[(colIndex++)]); } gBean.setBeanList(new ArrayList<FileReadAttributeBean>()); for (; colIndex < columns.size(); colIndex++) { FileReadAttributeBean fBean = new FileReadAttributeBean(); fBean.setProjectName( isProjectRegistration ? currProjectName : this.projectName); fBean.setAttributeName(columns.get(colIndex)); fBean.setAttributeValue(line[colIndex]); gBean.getBeanList().add(fBean); } this.gridList.add(gBean); } } lineCount++; } jobType = "grid"; } catch (Exception ex) { throw ex; } } } else if (jobType.equals("template")) { // download template List<EventMetaAttribute> emaList = readPersister.getEventMetaAttributes(projectName, eventName); /* * removing the sanity check on sample requirement since multiple sample support is in action * by hkim 5/2/13 ModelValidator validator = new ModelValidator(); validator.validateEventTemplateSanity(emaList, projectName, sampleName, eventName); */ TemplatePreProcessingUtils cvsUtils = new TemplatePreProcessingUtils(); String templateType = jobType.substring(jobType.indexOf("_") + 1); downloadStream = cvsUtils.buildFileContent(templateType, emaList, projectName, sampleName, eventName); downloadContentType = templateType.equals("c") ? "csv" : "vnd.ms-excel"; rtnVal = Constants.FILE_DOWNLOAD_MSG; } } } catch (Exception ex) { logger.error("Exception in EventLoader : " + ex.toString()); ex.printStackTrace(); if (ex.getClass() == ForbiddenResourceException.class) { addActionError(Constants.DENIED_USER_EDIT_MESSAGE); return Constants.FORBIDDEN_ACTION_RESPONSE; } else if (ex.getClass() == ForbiddenResourceException.class) { addActionError(Constants.DENIED_USER_EDIT_MESSAGE); return LOGIN; } else if (ex.getClass() == ParseException.class) addActionError(Constants.INVALID_DATE_MESSAGE); else { addActionError(ex.toString()); } // deletes uploaded files in event of error if (loadedFiles != null && loadedFiles.size() > 0) { for (String filePath : loadedFiles) { File tempFile = new File(fileStoragePath + filePath); if (tempFile.exists()) tempFile.delete(); } } try { if (tx != null) tx.rollback(); } catch (SystemException se) { addActionError(se.toString()); } rtnVal = ERROR; } finally { try { // get project list for the drop down box List<String> projectNameList = new ArrayList<String>(); if (projectNames == null || projectNames.equals("")) { projectNameList.add("ALL"); } else if (projectNames.contains(",")) { projectNameList.addAll(Arrays.asList(projectNames.split(","))); } else { projectNameList.add(projectNames); } projectList = readPersister.getProjects(projectNameList); if (tx != null && tx.getStatus() != Status.STATUS_NO_TRANSACTION) { tx.commit(); } if (jobType != null && jobType.equals("grid") && this.uploadFile != null) { this.uploadFile.delete(); } } catch (Exception ex) { ex.printStackTrace(); } } return rtnVal; }
/** * 現在のスレッド上でトランザクションがアクティブな場合は<code>true</code>を、それ以外の場合は<code>false</code>を返します。 * * @return 現在のスレッド上でトランザクションがアクティブな場合は<code>true</code> * @throws SystemException トランザクションマネージャで例外が発生した場合にスローされます * @see javax.transaction.UserTransaction#getStatus() */ protected boolean hasTransaction() throws SystemException { final int status = userTransaction.getStatus(); return status != STATUS_NO_TRANSACTION && status != STATUS_UNKNOWN; }
@Test public void testIsActive() throws Exception { expect(tx.getStatus()).andReturn(Status.STATUS_ACTIVE); replay(tx); assertTrue(jut.isActive()); }
@Test @FailureExpectedWithNewMetamodel( message = "ForeignKeyHelper.java:140 fails with org.hibernate.cfg.NotYetImplementedException: " + "No support yet for referenced join columns unless they correspond with columns bound for an attribute binding.") public void testPersistAndLoadUnderJta() throws Exception { Item item; SessionFactory sessionFactory = buildSessionFactory(); try { UserTransaction ut = (UserTransaction) ctx.lookup("UserTransaction"); ut.begin(); try { Session session = sessionFactory.openSession(); session.getTransaction().begin(); item = new Item("anItem", "An item owned by someone"); session.persist(item); session.getTransaction().commit(); session.close(); } catch (Exception e) { ut.setRollbackOnly(); throw e; } finally { if (ut.getStatus() == Status.STATUS_ACTIVE) ut.commit(); else ut.rollback(); } ut = (UserTransaction) ctx.lookup("UserTransaction"); ut.begin(); try { Session session = sessionFactory.openSession(); session.getTransaction().begin(); Item found = (Item) session.load(Item.class, item.getId()); Statistics stats = session.getSessionFactory().getStatistics(); log.info(stats.toString()); assertEquals(item.getDescription(), found.getDescription()); assertEquals(0, stats.getSecondLevelCacheMissCount()); assertEquals(1, stats.getSecondLevelCacheHitCount()); session.delete(found); session.getTransaction().commit(); session.close(); } catch (Exception e) { ut.setRollbackOnly(); throw e; } finally { if (ut.getStatus() == Status.STATUS_ACTIVE) ut.commit(); else ut.rollback(); } ut = (UserTransaction) ctx.lookup("UserTransaction"); ut.begin(); try { Session session = sessionFactory.openSession(); session.getTransaction().begin(); assertNull(session.get(Item.class, item.getId())); session.getTransaction().commit(); session.close(); } catch (Exception e) { ut.setRollbackOnly(); throw e; } finally { if (ut.getStatus() == Status.STATUS_ACTIVE) ut.commit(); else ut.rollback(); } } finally { if (sessionFactory != null) sessionFactory.close(); } }
/** * Import seed data when Seam Servlet fires an event notifying observers that the web application * is being initialized. */ public void importData(@Observes @Initialized WebApplication webapp) { log.info("Importing seed data for application " + webapp.getName()); // use manual transaction control since this is a managed bean try { utx.begin(); if (entityManager.createQuery("select g from Genre g").getResultList().size() == 0) { // AS7-2045 // entityManager.createQuery("delete from User").executeUpdate(); // // entityManager.createQuery("delete from Content").executeUpdate(); // entityManager.createQuery("delete from Genre").executeUpdate(); persist(users); for (TwoTuple<String, String> genre : genres) { if ("ИСТОРИИ".equals(genre.getFirst())) { createGenre( new Genre(genre.getFirst(), genre.getSecond()), Arrays.asList( new TwoTuple<Genre, List<Content>>( new Genre( "ЛИЧНЫЙ ОПЫТ", "Рассказ читателям о результатах собственных экспериментов."), new ArrayList<Content>()))); } else if ("ОБЗОРЫ".equals(genre.getFirst())) { createGenre( new Genre(genre.getFirst(), genre.getSecond()), Arrays.asList( new TwoTuple<Genre, List<Content>>( new Genre("ГАДЖЕТЫ", "Обзор гаджетов."), new ArrayList<Content>()))); } else if ("РАЗВЛЕЧЕНИЯ".equals(genre.getFirst())) { createGenre( new Genre(genre.getFirst(), genre.getSecond()), Arrays.asList( new TwoTuple<Genre, List<Content>>( new Genre("Юмор", "Анекдоты, шутки..."), new ArrayList<Content>()))); } else if ("ПРОЧЕЕ".equals(genre.getFirst())) { createGenre( new Genre(genre.getFirst(), genre.getSecond()), Arrays.asList( new TwoTuple<Genre, List<Content>>( new Genre("ВИДЕО", "Любительское видео"), new ArrayList<Content>()), new TwoTuple<Genre, List<Content>>( new Genre("ВИДЕО-КЛИПЫ", "Музыкальные видео клипы"), new ArrayList<Content>()))); } else { createGenre( new Genre(genre.getFirst(), genre.getSecond()), new ArrayList<TwoTuple<Genre, List<Content>>>()); } } } indextData(); utx.commit(); log.info("Seed data successfully imported"); } catch (Exception e) { log.error("Import failed. Seed data will not be available.", e); try { if (utx.getStatus() == Status.STATUS_ACTIVE) { try { utx.rollback(); } catch (Exception rbe) { log.error("Error rolling back transaction", rbe); } } } catch (Exception se) { } } }
@Test public void testCommit_2() throws Exception { expect(tx.getStatus()).andReturn(Status.STATUS_NO_TRANSACTION); replay(tx); jut.commit(); }
/** Upload an encoded Base64 file to the repository and decode it back once it's uploaded. */ @Override protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) { HashMap<String, Object> model = new HashMap<String, Object>(); UserTransaction trx = serviceRegistry.getTransactionService().getUserTransaction(); try { trx.begin(); System.out.println(trx.hashCode()); Element args = Arguments.getArguments(req); String username = args.getElementsByTagName(FORM_PARAM_USERNAME).item(0).getFirstChild().getNodeValue(); model.put(FTL_USERNAME, username); Impersonate.impersonate(username); String ref = DocumentUtils.pujarDocumentBase64(req, args, username).trim(); NodeRef nodeRef = new NodeRef(ref); Map<QName, Serializable> props = serviceRegistry.getNodeService().getProperties(nodeRef); ContentReader reader = serviceRegistry.getContentService().getReader(nodeRef, ContentModel.PROP_CONTENT); byte[] contentDecoded = es.mityc.firmaJava.libreria.utilidades.Base64.decode(reader.getContentString()); ContentWriter writer = serviceRegistry.getContentService().getWriter(nodeRef, ContentModel.PROP_CONTENT, true); writer.putContent(new ByteArrayInputStream(contentDecoded)); serviceRegistry.getOwnableService().setOwner(nodeRef, username); Context cx = Context.enter(); Scriptable scope = cx.initStandardObjects(); ScriptNode document = new ScriptNode(nodeRef, serviceRegistry, scope); model.put(FTL_DOCUMENT, document); model.put(FTL_SUCCESS, String.valueOf(true)); // Auditar creación de documento String type = document.getTypeShort(); String site = document.getSiteShortName(); if (type.equals("udl:documentSimple")) { AuditUdl.auditRecord( auditComponent, username, document.getNodeRef().toString(), AUDIT_ACTION_CREATE_DOCUMENT_SIMPLE, type, site); QName qNameIdDocSimple = QName.createQName( "http://www.smile.com/model/udl/1.0", "secuencial_identificador_documentSimple"); String idDocSimple = (String) serviceRegistry.getNodeService().getProperty(nodeRef, qNameIdDocSimple); if ("".equals(idDocSimple) || idDocSimple == null) { // serviceRegistry.getNodeService().deleteNode(nodeRef); throw new Exception("Error obtenint identificador via WebService."); } } trx.commit(); } catch (Exception e) { e.printStackTrace(); model.put(FTL_ERROR, e.getMessage()); model.put(FTL_SUCCESS, String.valueOf(false)); try { if (trx.getStatus() == javax.transaction.Status.STATUS_ACTIVE) { System.out.println(trx.hashCode()); trx.rollback(); } } catch (SystemException ex) { e.printStackTrace(); } } return model; }
@Test public void testRollback_2() throws Exception { expect(tx.getStatus()).andReturn(Status.STATUS_NO_TRANSACTION); replay(tx); jut.rollback(); }
@Test public void testIsActive_2() throws Exception { expect(tx.getStatus()).andReturn(Status.STATUS_UNKNOWN); replay(tx); assertFalse(jut.isActive()); }