Java Code Examples for javax.transaction.UserTransaction#begin()
The following examples show how to use
javax.transaction.UserTransaction#begin() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JPAResource.java From boost with Eclipse Public License 1.0 | 6 votes |
public void createThing(StringBuilder builder) throws NamingException, NotSupportedException, SystemException, IllegalStateException, SecurityException, HeuristicMixedException, HeuristicRollbackException, RollbackException { Context ctx = new InitialContext(); // Before getting an EntityManager, start a global transaction UserTransaction tran = (UserTransaction) ctx.lookup("java:comp/UserTransaction"); tran.begin(); // Now get the EntityManager from JNDI EntityManager em = (EntityManager) ctx.lookup(JNDI_NAME); builder.append("Creating a brand new Thing with " + em.getDelegate().getClass()).append(newline); // Create a Thing object and persist it to the database Thing thing = new Thing(); em.persist(thing); // Commit the transaction tran.commit(); int id = thing.getId(); builder.append("Created Thing " + id + ": " + thing).append(newline); }
Example 2
Source File: SiteServiceTestHuge.java From alfresco-repository with GNU Lesser General Public License v3.0 | 6 votes |
private void createUser(String userName) throws Exception { UserTransaction txn = transactionService.getUserTransaction(); try { txn.begin(); authenticationService.createAuthentication(userName, userName.toCharArray()); PropertyMap ppOne = new PropertyMap(4); ppOne.put(ContentModel.PROP_USERNAME, userName); ppOne.put(ContentModel.PROP_FIRSTNAME, userName.substring(0, userName.length()-4)); ppOne.put(ContentModel.PROP_LASTNAME, "user"); ppOne.put(ContentModel.PROP_EMAIL, userName + "@email.com"); ppOne.put(ContentModel.PROP_JOBTITLE, "jobTitle"); personService.createPerson(ppOne); txn.commit(); } catch (Exception e) { txn.rollback(); throw e; } }
Example 3
Source File: TransactionAwareSingletonTest.java From alfresco-repository with GNU Lesser General Public License v3.0 | 6 votes |
@Test public void testRollback() throws Throwable { UserTransaction txn = transactionService.getUserTransaction(); try { txn.begin(); singleton.put(INTEGER_TWO); check(INTEGER_TWO, true); check(null, false); // rollback txn.rollback(); } catch (Throwable e) { try { txn.rollback(); } catch (Throwable ee) {} throw e; } check(null, true); check(null, false); }
Example 4
Source File: TransactionAwareSingletonTest.java From alfresco-repository with GNU Lesser General Public License v3.0 | 6 votes |
@Test public void testCommit() throws Throwable { UserTransaction txn = transactionService.getUserTransaction(); try { txn.begin(); singleton.put(INTEGER_ONE); check(INTEGER_ONE, true); check(null, false); // commit txn.commit(); } catch (Throwable e) { try { txn.rollback(); } catch (Throwable ee) {} throw e; } check(INTEGER_ONE, true); check(INTEGER_ONE, false); }
Example 5
Source File: QueryAndJtaTest.java From gemfirexd-oss with Apache License 2.0 | 6 votes |
/** * verify that queries on indexes work with transaction * @see bug#40842 * @throws Exception */ public void testIndexOnCommitForPut() throws Exception { AttributesFactory af = new AttributesFactory(); af.setDataPolicy(DataPolicy.REPLICATE); Region region = cache.createRegion("sample", af.create()); qs.createIndex("foo", IndexType.FUNCTIONAL, "age", "/sample"); Context ctx = cache.getJNDIContext(); UserTransaction utx = (UserTransaction)ctx.lookup("java:/UserTransaction"); Integer x = new Integer(0); utx.begin(); region.create(x, new Person("xyz", 45)); utx.commit(); Query q = qs.newQuery("select * from /sample where age < 50"); assertEquals(1, ((SelectResults)q.execute()).size()); Person dsample = (Person)CopyHelper.copy(region.get(x)); dsample.setAge(55); utx.begin(); region.put(x, dsample); utx.commit(); System.out.println((region.get(x))); assertEquals(0, ((SelectResults) q.execute()).size()); }
Example 6
Source File: JPAWorkItemHandlerTest.java From jbpm-work-items with Apache License 2.0 | 6 votes |
@Test public void createOnProcessTest() throws Exception { String DESC = "Table"; Product p = new Product(DESC, 10f); startJPAWIHProcess(JPAWorkItemHandler.CREATE_ACTION, p); UserTransaction ut = getUserTransaction(); ut.begin(); EntityManager em = emf.createEntityManager(); TypedQuery<Product> products = em.createQuery("select p from Product p where p.description = :desc", Product.class); products.setParameter("desc", DESC); List<Product> resultList = products.getResultList(); Product result = resultList.iterator().next(); assertEquals(DESC, result.getDescription()); em.remove(result); em.flush(); em.close(); ut.commit(); }
Example 7
Source File: BeanTxSingletonBean.java From tomee with Apache License 2.0 | 5 votes |
public void openAccount(final Account acct, final Boolean rollback) throws RemoteException, RollbackException { try { final DataSource ds = (DataSource) jndiContext.lookup("java:comp/env/database"); final Connection con = ds.getConnection(); try { final UserTransaction ut = ejbContext.getUserTransaction(); /*[1] Begin the transaction */ ut.begin(); /*[2] Update the table */ final PreparedStatement stmt = con.prepareStatement("insert into Account (SSN, First_name, Last_name, Balance) values (?,?,?,?)"); try { stmt.setString(1, acct.getSsn()); stmt.setString(2, acct.getFirstName()); stmt.setString(3, acct.getLastName()); stmt.setInt(4, acct.getBalance()); stmt.executeUpdate(); } finally { stmt.close(); } /*[3] Commit or Rollback the transaction */ if (rollback.booleanValue()) ut.setRollbackOnly(); /*[4] Commit or Rollback the transaction */ ut.commit(); } finally { con.close(); } } catch (final RollbackException re) { throw re; } catch (final Exception e) { e.printStackTrace(); throw new RemoteException("[Bean] " + e.getClass().getName() + " : " + e.getMessage()); } }
Example 8
Source File: CacheTest.java From alfresco-repository with GNU Lesser General Public License v3.0 | 5 votes |
/** * Time how long it takes to create and complete a whole lot of transactions */ public void testInitializationPerformance() throws Exception { TransactionService transactionService = serviceRegistry.getTransactionService(); long start = System.nanoTime(); int count = 10000; for (int i = 0; i < count; i++) { UserTransaction txn = transactionService.getUserTransaction(); try { txn.begin(); transactionalCache.contains("A"); } finally { try { txn.rollback(); } catch (Throwable ee) {ee.printStackTrace();} } } long end = System.nanoTime(); // report System.out.println( "Cache initialization performance test: \n" + " count: " + count + "\n" + " transaction: " + (end-start)/((long)count) + " ns\\count"); }
Example 9
Source File: RetryingTransactionHelperTest.java From alfresco-repository with GNU Lesser General Public License v3.0 | 5 votes |
@Test public void testStartNewTransaction() throws Exception { // MNT-10096 class CustomListenerAdapter extends TransactionListenerAdapter { private String newTxnId; @Override public void afterRollback() { newTxnId = txnHelper.doInTransaction(new RetryingTransactionCallback<String>() { @Override public String execute() throws Throwable { return AlfrescoTransactionSupport.getTransactionId(); } }, true, false); } } UserTransaction txn = transactionService.getUserTransaction(); txn.begin(); String txnId = AlfrescoTransactionSupport.getTransactionId(); CustomListenerAdapter listener = new CustomListenerAdapter(); AlfrescoTransactionSupport.bindListener(listener); txn.rollback(); assertFalse("New transaction has not started", txnId.equals(listener.newTxnId)); }
Example 10
Source File: PolicyComponentTransactionTest.java From alfresco-repository with GNU Lesser General Public License v3.0 | 5 votes |
/** * Test for MNT-13836 (new API) * @throws Exception */ public void testIsEnabled2() throws Exception { UserTransaction transaction = trxService.getUserTransaction(); try { transaction.begin(); disableBehaviours(new ClassFilter(B_TYPE, false)); try { assertEquals("Incorrect behaviour state: global: ", true, behaviourFilter.isEnabled()); // A_TYPE assertEquals("Incorrect behaviour state: class: ", true, behaviourFilter.isEnabled(A_TYPE)); assertEquals("Incorrect behaviour state: classAndInstance", true, behaviourFilter.isEnabled(companyHome, A_TYPE)); assertEquals("Incorrect behaviour state: instance", true, behaviourFilter.isEnabled(companyHome)); // B_TYPE assertEquals("Incorrect behaviour state: class: ", false, behaviourFilter.isEnabled(B_TYPE)); assertEquals("Incorrect behaviour state: classAndInstance", false, behaviourFilter.isEnabled(companyHome, B_TYPE)); assertEquals("Incorrect behaviour state: instance", true, behaviourFilter.isEnabled(companyHome)); // C_TYPE assertEquals("Incorrect behaviour state: class: ", true, behaviourFilter.isEnabled(C_TYPE)); assertEquals("Incorrect behaviour state: classAndInstance", true, behaviourFilter.isEnabled(companyHome, C_TYPE)); assertEquals("Incorrect behaviour state: instance", true, behaviourFilter.isEnabled(companyHome)); } finally { behaviourFilter.enableBehaviour(B_TYPE); } transaction.commit(); } catch(Exception e) { try { transaction.rollback(); } catch (IllegalStateException ee) {} throw e; } }
Example 11
Source File: DbNodeServiceImplTest.java From alfresco-repository with GNU Lesser General Public License v3.0 | 5 votes |
/** * Deletes a child node and then iterates over the children of the parent node, * getting the QName. This caused some issues after we did some optimization * using lazy loading of the associations. */ public void testLazyLoadIssue() throws Exception { Map<QName, ChildAssociationRef> assocRefs = buildNodeGraph(); // commit results TestTransaction.flagForCommit(); TestTransaction.end(); UserTransaction userTransaction = txnService.getUserTransaction(); try { userTransaction.begin(); ChildAssociationRef n6pn8Ref = assocRefs.get(QName.createQName(BaseNodeServiceTest.NAMESPACE, "n6_p_n8")); NodeRef n6Ref = n6pn8Ref.getParentRef(); NodeRef n8Ref = n6pn8Ref.getChildRef(); // delete n8 nodeService.deleteNode(n8Ref); // get the parent children List<ChildAssociationRef> assocs = nodeService.getChildAssocs(n6Ref); for (ChildAssociationRef assoc : assocs) { // just checking } userTransaction.commit(); } catch(Exception e) { try { userTransaction.rollback(); } catch (IllegalStateException ee) {} throw e; } }
Example 12
Source File: FileFolderServiceImplTest.java From alfresco-repository with GNU Lesser General Public License v3.0 | 5 votes |
public void testGetReaderWriter() throws Exception { // testing a failure txn.commit(); txn = transactionService.getUserTransaction(); txn.begin(); FileInfo dirInfo = getByName(NAME_L0_FOLDER_A, true); UserTransaction rollbackTxn = null; try { rollbackTxn = transactionService.getNonPropagatingUserTransaction(); rollbackTxn.begin(); fileFolderService.getWriter(dirInfo.getNodeRef()); fail("Failed to detect content write to folder"); } catch (RuntimeException e) { // expected } finally { rollbackTxn.rollback(); } FileInfo fileInfo = getByName(NAME_L1_FILE_A, false); ContentWriter writer = fileFolderService.getWriter(fileInfo.getNodeRef()); assertNotNull("Writer is null", writer); // write some content String content = "ABC"; writer.putContent(content); // read the content ContentReader reader = fileFolderService.getReader(fileInfo.getNodeRef()); assertNotNull("Reader is null", reader); String checkContent = reader.getContentString(); assertEquals("Content mismatch", content, checkContent); }
Example 13
Source File: ImapMessageTest.java From alfresco-repository with GNU Lesser General Public License v3.0 | 4 votes |
public void testMessageRenamedBetweenReads() throws Exception { // Get test message UID final Long uid = getMessageUid(folder, 1); // Get Message size final int count = getMessageSize(folder, uid); // Get first part // Split the message into 2 part using a non multiple of 4 - 103 is a prime number // as the BASE64Decoder may not throw the IOException // see MNT-12995 BODY body = getMessageBodyPart(folder, uid, 0, count - 103); // Rename message. The size of letter describing the node will change // These changes should be committed because it should be visible from client NodeRef contentNode = findNode(companyHomePathInStore + TEST_FILE); UserTransaction txn = transactionService.getUserTransaction(); txn.begin(); fileFolderService.rename(contentNode, "testtesttesttesttesttesttesttesttesttest"); txn.commit(); // Read second message part BODY bodyRest = getMessageBodyPart(folder, uid, count - 103, 103); // Creating and parsing message from 2 parts MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()), new SequenceInputStream(new BufferedInputStream(body.getByteArrayInputStream()), new BufferedInputStream(bodyRest.getByteArrayInputStream()))); // Reading first part - should be successful MimeMultipart content = (MimeMultipart) message.getContent(); assertNotNull(content.getBodyPart(0).getContent()); try { // Reading second part cause error content.getBodyPart(1).getContent(); fail("Should raise an IOException"); } catch (IOException e) { } }
Example 14
Source File: ReplicationServiceIntegrationTest.java From alfresco-repository with GNU Lesser General Public License v3.0 | 4 votes |
/** * Check that cancelling works. * Does this by taking a lock on the job, cancelling, * releasing and seeing it abort. * * Tests that when we ask for a replication task to be cancelled, * that it starts, cancels, and the status is correctly recorded * for it. */ public void testReplicationExecutionCancelling() throws Exception { // We need the test transfer target for this test makeTransferTarget(); // Create a task ReplicationDefinition rd = replicationService.createReplicationDefinition(ACTION_NAME, "Test"); rd.setTargetName(TRANSFER_TARGET); rd.getPayload().add(folder1); rd.getPayload().add(folder2); // Get the lock for 2 seconds String token = jobLockService.getLock( rd.getReplicationQName(), 2 * 1000, 1, 1 ); // Request it be run async UserTransaction txn = transactionService.getUserTransaction(); txn.begin(); actionService.executeAction(rd, replicationRoot, false, true); assertEquals(ActionStatus.Pending, rd.getExecutionStatus()); assertEquals(false, actionTrackingService.isCancellationRequested(rd)); actionTrackingService.requestActionCancellation(rd); assertEquals(true, actionTrackingService.isCancellationRequested(rd)); txn.commit(); // Let it get going, will be waiting for the lock // having registered with the action tracking service for(int i=0; i<100; i++) { // Keep asking for it to be cancelled ASAP actionTrackingService.requestActionCancellation(rd); if(rd.getExecutionStatus().equals(ActionStatus.Running)) { // Good, has started up // Stop waiting and do the cancel break; } else { // Still pending, wait a bit more Thread.sleep(10); } } // Ensure it started, and should shortly stop assertEquals(ActionStatus.Running, rd.getExecutionStatus()); assertEquals(true, actionTrackingService.isCancellationRequested(rd)); // Release our lock, should allow the replication task // to get going and spot the cancel jobLockService.releaseLock(token, rd.getReplicationQName()); // Let the main replication task run to cancelled/completed // This can take quite some time though... for(int i=0; i<10; i++) { if(rd.getExecutionStatus() == ActionStatus.Running) { Thread.sleep(1000); } else { // It has finished running, check it break; } } // Ensure it was cancelled assertEquals(null, rd.getExecutionFailureMessage()); assertNotNull(rd.getLocalTransferReport()); assertNotNull(rd.getRemoteTransferReport()); assertEquals(ActionStatus.Cancelled, rd.getExecutionStatus()); }
Example 15
Source File: TradeDirect.java From sample.daytrader7 with Apache License 2.0 | 4 votes |
/** * @see TradeServices#buy(String, String, double) */ @Override public OrderDataBean buy(String userID, String symbol, double quantity, int orderProcessingMode) throws Exception { final Connection conn = getConn(); OrderDataBean orderData = null; UserTransaction txn = null; BigDecimal total; try { if (Log.doTrace()) { Log.trace("TradeDirect:buy - inSession(" + this.inSession + ")", userID, symbol, new Double(quantity)); } if (!inSession && orderProcessingMode == TradeConfig.ASYNCH_2PHASE) { if (Log.doTrace()) { Log.trace("TradeDirect:buy create/begin global transaction"); } // FUTURE the UserTransaction be looked up once txn = (javax.transaction.UserTransaction) context.lookup("java:comp/UserTransaction"); txn.begin(); setInGlobalTxn(true); } //conn = getConn(); AccountDataBean accountData = getAccountData(conn, userID); QuoteDataBean quoteData = getQuoteData(conn, symbol); HoldingDataBean holdingData = null; // the buy operation will create // the holding orderData = createOrder(conn, accountData, quoteData, holdingData, "buy", quantity); // Update -- account should be credited during completeOrder BigDecimal price = quoteData.getPrice(); BigDecimal orderFee = orderData.getOrderFee(); total = (new BigDecimal(quantity).multiply(price)).add(orderFee); // subtract total from account balance creditAccountBalance(conn, accountData, total.negate()); final Integer orderID = orderData.getOrderID(); try { if (orderProcessingMode == TradeConfig.SYNCH) { completeOrder(conn,orderID); } else { commit(conn); queueOrder(orderID, true); // 2-phase } } catch (JMSException je) { Log.error("TradeBean:buy(" + userID + "," + symbol + "," + quantity + ") --> failed to queueOrder", je); /* On exception - cancel the order */ cancelOrder(conn, orderData.getOrderID()); } orderData = getOrderData(conn, orderData.getOrderID().intValue()); if (txn != null) { if (Log.doTrace()) { Log.trace("TradeDirect:buy committing global transaction"); } txn.commit(); setInGlobalTxn(false); } else { commit(conn); } } catch (Exception e) { Log.error("TradeDirect:buy error - rolling back", e); if (getInGlobalTxn()) { txn.rollback(); } else { rollBack(conn, e); } } finally { releaseConn(conn); } return orderData; }
Example 16
Source File: ReplicationRestApiTest.java From alfresco-remote-api with GNU Lesser General Public License v3.0 | 4 votes |
/** * Test that when creating and working with replication * definitions with a name that includes "nasty" * characters, things still work. * Related to ALF-4610. */ public void testReplicationDefinitionsNastyNames() throws Exception { AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName()); Response response; String jsonStr; String nastyName = "~!@#$%^&()_+-={}[];"; String nastyNameURL = URLEncoder.encodeUriComponent(nastyName); // Create JSONObject json = new JSONObject(); json.put("name", nastyName); json.put("description", "Nasty Characters"); response = sendRequest(new PostRequest(URL_DEFINITIONS, json.toString(), JSON), Status.STATUS_OK); assertEquals(Status.STATUS_OK, response.getStatus()); jsonStr = response.getContentAsString(); json = new JSONObject(jsonStr).getJSONObject("data"); assertNotNull(json); assertEquals(nastyName, json.get("name")); assertEquals("Nasty Characters", json.get("description")); assertEquals("New", json.get("status")); assertEquals(JSONObject.NULL, json.get("startedAt")); assertEquals(JSONObject.NULL, json.get("endedAt")); assertEquals(JSONObject.NULL, json.get("failureMessage")); assertEquals(JSONObject.NULL, json.get("executionDetails")); assertEquals(JSONObject.NULL, json.get("transferLocalReport")); assertEquals(JSONObject.NULL, json.get("transferRemoteReport")); assertEquals(true, json.get("enabled")); assertEquals(JSONObject.NULL, json.get("targetName")); assertEquals(0, json.getJSONArray("payload").length()); // Check it turned up assertEquals(1, replicationService.loadReplicationDefinitions().size()); assertEquals(nastyName, replicationService.loadReplicationDefinitions().get(0).getReplicationName()); // Fetch the details response = sendRequest(new GetRequest(URL_DEFINITION + nastyNameURL), 200); assertEquals(Status.STATUS_OK, response.getStatus()); jsonStr = response.getContentAsString(); json = new JSONObject(jsonStr).getJSONObject("data"); assertNotNull(json); assertEquals(nastyName, json.get("name")); assertEquals("Nasty Characters", json.get("description")); assertEquals("New", json.get("status")); // Delete // Because some of the delete operations happen post-commit, and // because we don't have real transactions, fake it UserTransaction txn = transactionService.getUserTransaction(); txn.begin(); // Call the delete webscript response = sendRequest(new DeleteRequest(URL_DEFINITION + nastyNameURL), Status.STATUS_NO_CONTENT); assertEquals(Status.STATUS_NO_CONTENT, response.getStatus()); // Let the node service do its work txn.commit(); Thread.sleep(50); // Check the details webscript to ensure it went response = sendRequest(new GetRequest(URL_DEFINITION + nastyNameURL), Status.STATUS_NOT_FOUND); assertEquals(Status.STATUS_NOT_FOUND, response.getStatus()); // And check the service too assertEquals(0, replicationService.loadReplicationDefinitions().size()); }
Example 17
Source File: RuleServiceImplTest.java From alfresco-repository with GNU Lesser General Public License v3.0 | 4 votes |
/** * ALF-12726 * use NodeService to rename */ @Test public void testOutboundRuleTriggeredAfterRename2() throws Exception { UserTransaction txn = transactionService.getUserTransaction(); txn.begin(); String newName = "newName" + GUID.generate(); // Create 2 folders NodeRef folder1NodeRef = this.nodeService.createNode(rootNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName("parentnode" + GUID.generate()), ContentModel.TYPE_FOLDER) .getChildRef(); NodeRef folder2NodeRef = this.nodeService.createNode(rootNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName("parentnode" + GUID.generate()), ContentModel.TYPE_FOLDER) .getChildRef(); // Create rule for folder1 Rule testRule = new Rule(); testRule.setRuleTypes(Collections.singletonList(RuleType.OUTBOUND)); testRule.setTitle("RuleServiceTest" + GUID.generate()); testRule.setDescription(DESCRIPTION); testRule.applyToChildren(true); Action action = this.actionService.createAction(CopyActionExecuter.NAME); action.setParameterValue(CopyActionExecuter.PARAM_DESTINATION_FOLDER, folder2NodeRef); testRule.setAction(action); this.ruleService.saveRule(folder1NodeRef, testRule); assertNotNull("Rule was not saved", testRule.getNodeRef()); QName actionedQName = QName.createQName("actioneduponnode" + GUID.generate()); // New node NodeRef actionedUponNodeRef = this.nodeService.createNode(folder1NodeRef, ContentModel.ASSOC_CHILDREN, actionedQName, ContentModel.TYPE_CONTENT).getChildRef(); ContentWriter writer = this.contentService.getWriter(actionedUponNodeRef, ContentModel.PROP_CONTENT, true); writer.setMimetype("text/plain"); writer.putContent("TestContent"); // Rename the node nodeService.setProperty(actionedUponNodeRef, ContentModel.PROP_NAME, newName); txn.commit(); txn = transactionService.getUserTransaction(); txn.begin(); // Check that the rule was not executed List<ChildAssociationRef> childAssoc = this.nodeService.getChildAssocs(folder2NodeRef, RegexQNamePattern.MATCH_ALL, actionedQName); assertEquals("The rule should not be triggered and no document should be present.", 0, childAssoc.size()); // Check that the content is still in folder1 childAssoc = this.nodeService.getChildAssocs(folder1NodeRef, RegexQNamePattern.MATCH_ALL, actionedQName); assertEquals("The rule should not be triggered and the document should be in folder1.", 1, childAssoc.size()); assertEquals("The node should be renamed.", newName, nodeService.getProperty(actionedUponNodeRef, ContentModel.PROP_NAME)); this.nodeService.deleteNode(folder1NodeRef); this.nodeService.deleteNode(folder2NodeRef); txn.commit(); }
Example 18
Source File: SpringAwareUserTransactionTest.java From alfresco-core with GNU Lesser General Public License v3.0 | 4 votes |
public void getTrx() throws Exception { UserTransaction txn = getTxn(); txn.begin(); txn = null; }
Example 19
Source File: BMXATestBean.java From gemfirexd-oss with Apache License 2.0 | 4 votes |
@RemoteMethod public void testXACommitRollbackWithJMS(boolean toCommit, int dstype) throws GemFireXDXATestException { JMSQueueHelper jms = null; Connection gfxdConn = null; try { Context ictx = new InitialContext(); Context env = (Context) ictx.lookup("java:comp/env"); String queueConnFactoryName = (String) env.lookup("queueConnFactoryName"); String queueName = (String) env.lookup("queueName"); jms = new JMSQueueHelper(ictx, queueConnFactoryName, queueName); jms.init(); String gfxdXADSName = (String) env.lookup(getGemFireXDDSName(dstype)); DataSource gfxdxads = (DataSource) ictx.lookup(gfxdXADSName); gfxdConn = gfxdxads.getConnection(); String tableName = (String) env.lookup("tableName"); UserTransaction utx = getSessionContext().getUserTransaction(); utx.begin(); log("BM TRANSACTION BEGUN"); String msgText = jms.receive(); if (msgText == null) { log("***WARN!! Message is null**** "); return; } else { updateDatabase(gfxdConn, tableName, msgText); } if (toCommit) { utx.commit(); log("BM TRANSACTION COMMIT"); } else { utx.rollback(); log("BM TRANSACTION ROLLBACK"); } } catch (NamingException nex) { log("Naming exception: " + nex); throw new GemFireXDXATestException("Failed in test setting: ", nex); } catch (JMSException jex) { log("JMS exception: " + jex); throw new GemFireXDXATestException("Failed in test setting: ", jex); } catch (SQLException sqle) { log("SQL exception: " + sqle); throw new GemFireXDXATestException("Failed in test setting: ", sqle); } catch (Exception e) { log("EXCEPTION: " + e); } finally { jms.closeReceiver(); if (gfxdConn != null) { try { gfxdConn.close(); } catch (SQLException ex) { } } } }
Example 20
Source File: RuleServiceCoverageTest.java From alfresco-repository with GNU Lesser General Public License v3.0 | 4 votes |
/** * Test image transformation * */ public void testImageTransformAction() throws Throwable { Map<String, Serializable> params = new HashMap<String, Serializable>(1); params.put(ImageTransformActionExecuter.PARAM_DESTINATION_FOLDER, this.rootNodeRef); params.put(ImageTransformActionExecuter.PARAM_ASSOC_TYPE_QNAME, ContentModel.ASSOC_CHILDREN); params.put(TransformActionExecuter.PARAM_MIME_TYPE, MimetypeMap.MIMETYPE_IMAGE_JPEG); params.put(ImageTransformActionExecuter.PARAM_ASSOC_QNAME, QName.createQName(TEST_NAMESPACE, "transformed")); params.put(ImageTransformActionExecuter.PARAM_CONVERT_COMMAND, "-negate"); Rule rule = createRule( RuleType.INBOUND, ImageTransformActionExecuter.NAME, params, NoConditionEvaluator.NAME, null); this.ruleService.saveRule(this.nodeRef, rule); UserTransaction tx = transactionService.getUserTransaction(); tx.begin(); Map<QName, Serializable> props =new HashMap<QName, Serializable>(1); props.put(ContentModel.PROP_NAME, "test.gif"); // Create the node at the root NodeRef newNodeRef = this.nodeService.createNode( this.nodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName(TEST_NAMESPACE, "origional"), ContentModel.TYPE_CONTENT, props).getChildRef(); // Set some content on the origional ContentWriter contentWriter = this.contentService.getWriter(newNodeRef, ContentModel.PROP_CONTENT, true); contentWriter.setMimetype(MimetypeMap.MIMETYPE_IMAGE_GIF); File testFile = AbstractContentTransformerTest.loadQuickTestFile("gif"); contentWriter.putContent(testFile); tx.commit(); //System.out.println(NodeStoreInspector.dumpNodeStore(this.nodeService, this.testStoreRef)); // Check that the created node is still there List<ChildAssociationRef> origRefs = this.nodeService.getChildAssocs( this.nodeRef, RegexQNamePattern.MATCH_ALL, QName.createQName(TEST_NAMESPACE, "origional")); assertNotNull(origRefs); assertEquals(1, origRefs.size()); NodeRef origNodeRef = origRefs.get(0).getChildRef(); assertEquals(newNodeRef, origNodeRef); // Check that the created node has been copied List<ChildAssociationRef> copyChildAssocRefs = this.nodeService.getChildAssocs( this.rootNodeRef, RegexQNamePattern.MATCH_ALL, QName.createQName(TEST_NAMESPACE, "test.jpg")); assertNotNull(copyChildAssocRefs); assertEquals(1, copyChildAssocRefs.size()); NodeRef copyNodeRef = copyChildAssocRefs.get(0).getChildRef(); assertTrue(this.nodeService.hasAspect(copyNodeRef, ContentModel.ASPECT_COPIEDFROM)); NodeRef source = copyService.getOriginal(copyNodeRef); assertEquals(newNodeRef, source); }