Example usage for javax.transaction UserTransaction begin

List of usage examples for javax.transaction UserTransaction begin

Introduction

In this page you can find the example usage for javax.transaction UserTransaction begin.

Prototype

void begin() throws NotSupportedException, SystemException;

Source Link

Document

Create a new transaction and associate it with the current thread.

Usage

From source file:org.alfresco.repo.cache.CacheTest.java

/** Lock values and ensure they don't get modified */
public void testValueLockingInTxn() throws Exception {
    // add item to global cache
    TransactionalCache.putSharedCacheValue(backingCache, DEFINITIVE_TWO, "initial_two", null);
    TransactionalCache.putSharedCacheValue(backingCache, DEFINITIVE_THREE, "initial_three", null);

    TransactionService transactionService = serviceRegistry.getTransactionService();
    UserTransaction txn = transactionService.getUserTransaction();
    try {/*from w  w  w  . j a  v a  2 s.  co m*/
        // begin a transaction
        txn.begin();

        // Add
        {
            assertEquals(null, transactionalCache.get(DEFINITIVE_ONE));
            // Add it
            transactionalCache.put(DEFINITIVE_ONE, DEFINITIVE_ONE);
            assertFalse("Key should not be locked, yet.", transactionalCache.isValueLocked(DEFINITIVE_ONE));
            // Mark it as definitive
            transactionalCache.lockValue(DEFINITIVE_ONE);
            assertTrue("Key should be locked.", transactionalCache.isValueLocked(DEFINITIVE_ONE));
            // Attempt update
            transactionalCache.put(DEFINITIVE_ONE, "update_one");
            assertEquals("Update values should be locked.", DEFINITIVE_ONE,
                    transactionalCache.get(DEFINITIVE_ONE));
        }

        // Update
        {
            assertEquals("initial_two", transactionalCache.get(DEFINITIVE_TWO));
            // Update it
            transactionalCache.put(DEFINITIVE_TWO, DEFINITIVE_TWO);
            assertFalse("Key should not be locked, yet.", transactionalCache.isValueLocked(DEFINITIVE_TWO));
            // Mark it as definitive
            transactionalCache.lockValue(DEFINITIVE_TWO);
            assertTrue("Key should be locked.", transactionalCache.isValueLocked(DEFINITIVE_TWO));
            // Attempt update
            transactionalCache.put(DEFINITIVE_TWO, "update_two");
            assertEquals("Update values should be locked.", DEFINITIVE_TWO,
                    transactionalCache.get(DEFINITIVE_TWO));
            // Attempt removal
            transactionalCache.remove(DEFINITIVE_TWO);
            assertEquals("Update values should be locked.", DEFINITIVE_TWO,
                    transactionalCache.get(DEFINITIVE_TWO));
        }

        // Remove
        {
            assertEquals("initial_three", transactionalCache.get(DEFINITIVE_THREE));
            // Remove it
            transactionalCache.remove(DEFINITIVE_THREE);
            assertFalse("Key should not be locked, yet.", transactionalCache.isValueLocked(DEFINITIVE_THREE));
            // Mark it as definitive
            transactionalCache.lockValue(DEFINITIVE_THREE);
            assertTrue("Key should be locked.", transactionalCache.isValueLocked(DEFINITIVE_THREE));
            // Attempt update
            transactionalCache.put(DEFINITIVE_THREE, "add_three");
            assertEquals("Removal should be locked.", null, transactionalCache.get(DEFINITIVE_THREE));
        }

        txn.commit();

        // Check post-commit values
        assertEquals("Definitive change not written through.", DEFINITIVE_ONE,
                TransactionalCache.getSharedCacheValue(backingCache, DEFINITIVE_ONE, null));
        assertEquals("Definitive change not written through.", DEFINITIVE_TWO,
                TransactionalCache.getSharedCacheValue(backingCache, DEFINITIVE_TWO, null));
        assertEquals("Definitive change not written through.", null,
                TransactionalCache.getSharedCacheValue(backingCache, DEFINITIVE_THREE, null));
    } finally {
        try {
            txn.rollback();
        } catch (Throwable ee) {
        }
    }
}

From source file:org.alfresco.repo.cache.CacheTest.java

public void testTransactionalCacheStatsOnCommit() throws Throwable {
    // add item to global cache
    TransactionalCache.putSharedCacheValue(backingCache, "stats-test1", "v", null);
    TransactionalCache.putSharedCacheValue(backingCache, "stats-test2", "v", null);
    TransactionalCache.putSharedCacheValue(backingCache, "stats-test3", "v", null);

    TransactionService transactionService = serviceRegistry.getTransactionService();
    UserTransaction txn = transactionService.getUserTransaction();

    final long hitsAtStart = cacheStats.count("transactionalCache", OpType.GET_HIT);
    final long missesAtStart = cacheStats.count("transactionalCache", OpType.GET_MISS);
    final long putsAtStart = cacheStats.count("transactionalCache", OpType.PUT);
    final long removesAtStart = cacheStats.count("transactionalCache", OpType.REMOVE);
    final long clearsAtStart = cacheStats.count("transactionalCache", OpType.CLEAR);

    try {//ww w .j a v  a  2s  .c  om
        // begin a transaction
        txn.begin();

        // Perform some puts
        transactionalCache.put("stats-test4", "v");
        transactionalCache.put("stats-test5", "v");
        transactionalCache.put("stats-test6", "v");
        transactionalCache.put("stats-test7", "v");
        transactionalCache.put("stats-test8", "v");

        // Perform some gets...
        // hits
        transactionalCache.get("stats-test3");
        transactionalCache.get("stats-test2");
        transactionalCache.get("stats-test1");
        // repeated hits won't touch the shared cache
        transactionalCache.get("stats-test2");
        transactionalCache.get("stats-test1");
        // misses - not yet committed
        transactionalCache.get("stats-miss1");
        transactionalCache.get("stats-miss2");
        transactionalCache.get("stats-miss3");
        transactionalCache.get("stats-miss4");
        // repeated misses won't touch the shared cache
        transactionalCache.get("stats-miss2");
        transactionalCache.get("stats-miss3");

        // Perform some removals
        transactionalCache.remove("stats-test1");
        transactionalCache.remove("stats-test2");
        transactionalCache.remove("stats-test3");
        transactionalCache.remove("stats-test9");
        transactionalCache.remove("stats-test10");
        transactionalCache.remove("stats-test11");
        transactionalCache.remove("stats-test12");
        transactionalCache.remove("stats-test13");

        // Check nothing has changed yet - changes not written through until commit or rollback
        assertEquals(hitsAtStart, cacheStats.count("transactionalCache", OpType.GET_HIT));
        assertEquals(missesAtStart, cacheStats.count("transactionalCache", OpType.GET_MISS));
        assertEquals(putsAtStart, cacheStats.count("transactionalCache", OpType.PUT));
        assertEquals(removesAtStart, cacheStats.count("transactionalCache", OpType.REMOVE));
        assertEquals(clearsAtStart, cacheStats.count("transactionalCache", OpType.CLEAR));

        // commit the transaction
        txn.commit();

        // TODO: remove is called twice for each remove (in beforeCommit and afterCommit) - check this is correct.
        assertEquals(removesAtStart + 16, cacheStats.count("transactionalCache", OpType.REMOVE));
        assertEquals(hitsAtStart + 3, cacheStats.count("transactionalCache", OpType.GET_HIT));
        assertEquals(missesAtStart + 4, cacheStats.count("transactionalCache", OpType.GET_MISS));
        assertEquals(putsAtStart + 5, cacheStats.count("transactionalCache", OpType.PUT));
        // Performing a clear would affect the other stats, so a separate test is required.
        assertEquals(clearsAtStart + 0, cacheStats.count("transactionalCache", OpType.CLEAR));
    } catch (Throwable e) {
        if (txn.getStatus() == Status.STATUS_ACTIVE) {
            txn.rollback();
        }
        throw e;
    }
}

From source file:org.alfresco.repo.cache.CacheTest.java

public void testTransactionalCacheStatsDisabled() throws Throwable {
    // add item to global cache
    TransactionalCache.putSharedCacheValue(backingCacheNoStats, "stats-test1", "v", null);
    TransactionalCache.putSharedCacheValue(backingCacheNoStats, "stats-test2", "v", null);
    TransactionalCache.putSharedCacheValue(backingCacheNoStats, "stats-test3", "v", null);

    TransactionService transactionService = serviceRegistry.getTransactionService();
    UserTransaction txn = transactionService.getUserTransaction();

    for (OpType opType : OpType.values()) {
        try {/*from w  ww  .  j  av a 2 s .  c  o  m*/
            cacheStats.count("transactionalCacheNoStats", opType);
            fail("Expected NoStatsForCache error.");
        } catch (NoStatsForCache e) {
            // Good
        }
    }

    try {
        // begin a transaction
        txn.begin();

        // Perform some puts
        transactionalCacheNoStats.put("stats-test4", "v");
        transactionalCache.put("stats-test5", "v");
        transactionalCache.put("stats-test6", "v");
        transactionalCache.put("stats-test7", "v");
        transactionalCache.put("stats-test8", "v");

        // Perform some gets...
        // hits
        transactionalCache.get("stats-test3");
        transactionalCache.get("stats-test2");
        transactionalCache.get("stats-test1");
        // repeated hits won't touch the shared cache
        transactionalCache.get("stats-test2");
        transactionalCache.get("stats-test1");
        // misses - not yet committed
        transactionalCache.get("stats-miss1");
        transactionalCache.get("stats-miss2");
        transactionalCache.get("stats-miss3");
        transactionalCache.get("stats-miss4");
        // repeated misses won't touch the shared cache
        transactionalCache.get("stats-miss2");
        transactionalCache.get("stats-miss3");

        // Perform some removals
        transactionalCache.remove("stats-test1");
        transactionalCache.remove("stats-test2");
        transactionalCache.remove("stats-test3");
        transactionalCache.remove("stats-test9");
        transactionalCache.remove("stats-test10");
        transactionalCache.remove("stats-test11");
        transactionalCache.remove("stats-test12");
        transactionalCache.remove("stats-test13");

        // Check nothing has changed - changes not written through until commit or rollback
        for (OpType opType : OpType.values()) {
            try {
                cacheStats.count("transactionalCacheNoStats", opType);
                fail("Expected NoStatsForCache error.");
            } catch (NoStatsForCache e) {
                // Good
            }
        }

        // commit the transaction
        txn.commit();

        // Post-commit, nothing should have changed.
        for (OpType opType : OpType.values()) {
            try {
                cacheStats.count("transactionalCacheNoStats", opType);
                fail("Expected NoStatsForCache error.");
            } catch (NoStatsForCache e) {
                // Good
            }
        }
    } catch (Throwable e) {
        if (txn.getStatus() == Status.STATUS_ACTIVE) {
            txn.rollback();
        }
        throw e;
    }
}

From source file:org.alfresco.repo.cache.CacheTest.java

public void testTransactionalCacheStatsForClears() throws Throwable {
    // add item to global cache
    TransactionalCache.putSharedCacheValue(backingCache, "stats-test1", "v", null);
    TransactionalCache.putSharedCacheValue(backingCache, "stats-test2", "v", null);
    TransactionalCache.putSharedCacheValue(backingCache, "stats-test3", "v", null);

    TransactionService transactionService = serviceRegistry.getTransactionService();
    UserTransaction txn = transactionService.getUserTransaction();

    final long hitsAtStart = cacheStats.count("transactionalCache", OpType.GET_HIT);
    final long missesAtStart = cacheStats.count("transactionalCache", OpType.GET_MISS);
    final long putsAtStart = cacheStats.count("transactionalCache", OpType.PUT);
    final long removesAtStart = cacheStats.count("transactionalCache", OpType.REMOVE);
    final long clearsAtStart = cacheStats.count("transactionalCache", OpType.CLEAR);

    try {//from   w  w w .  j av a2 s . c  om
        // begin a transaction
        txn.begin();

        // Perform some puts
        transactionalCache.put("stats-test4", "v");
        transactionalCache.put("stats-test5", "v");
        transactionalCache.put("stats-test6", "v");
        transactionalCache.put("stats-test7", "v");
        transactionalCache.put("stats-test8", "v");

        // Perform some gets...
        // hits
        transactionalCache.get("stats-test3");
        transactionalCache.get("stats-test2");
        transactionalCache.get("stats-test1");
        // repeated hits won't touch the shared cache
        transactionalCache.get("stats-test2");
        transactionalCache.get("stats-test1");
        // misses - not yet committed
        transactionalCache.get("stats-miss1");
        transactionalCache.get("stats-miss2");
        transactionalCache.get("stats-miss3");
        transactionalCache.get("stats-miss4");
        // repeated misses won't touch the shared cache
        transactionalCache.get("stats-miss2");
        transactionalCache.get("stats-miss3");

        // Perform some removals
        transactionalCache.remove("stats-test1");
        transactionalCache.remove("stats-test2");
        transactionalCache.remove("stats-test3");
        transactionalCache.remove("stats-test9");
        transactionalCache.remove("stats-test10");
        transactionalCache.remove("stats-test11");
        transactionalCache.remove("stats-test12");
        transactionalCache.remove("stats-test13");

        // Perform some clears
        transactionalCache.clear();
        transactionalCache.clear();

        // Check nothing has changed yet - changes not written through until commit or rollback
        assertEquals(hitsAtStart, cacheStats.count("transactionalCache", OpType.GET_HIT));
        assertEquals(missesAtStart, cacheStats.count("transactionalCache", OpType.GET_MISS));
        assertEquals(putsAtStart, cacheStats.count("transactionalCache", OpType.PUT));
        assertEquals(removesAtStart, cacheStats.count("transactionalCache", OpType.REMOVE));
        assertEquals(clearsAtStart, cacheStats.count("transactionalCache", OpType.CLEAR));

        // commit the transaction
        txn.commit();

        assertEquals(clearsAtStart + 2, cacheStats.count("transactionalCache", OpType.CLEAR));
        // There are no removes or puts propagated to the shared cache, as a result of the clears.
        assertEquals(removesAtStart + 0, cacheStats.count("transactionalCache", OpType.REMOVE));
        assertEquals(putsAtStart + 0, cacheStats.count("transactionalCache", OpType.PUT));
        assertEquals(hitsAtStart + 3, cacheStats.count("transactionalCache", OpType.GET_HIT));
        assertEquals(missesAtStart + 4, cacheStats.count("transactionalCache", OpType.GET_MISS));
    } catch (Throwable e) {
        if (txn.getStatus() == Status.STATUS_ACTIVE) {
            txn.rollback();
        }
        throw e;
    }
}

From source file:org.alfresco.repo.domain.audit.AuditDAOTest.java

private void scriptCanDeleteOrphanedPropsWork(final boolean performance) throws Exception {
    final int iterationStep, maxIterations;
    if (performance) {
        iterationStep = 1000;/*from ww w  .j a v  a 2 s. c o m*/
        maxIterations = 1000;
    } else {
        iterationStep = 1;
        maxIterations = 1;
    }

    UserTransaction txn;

    for (int i = iterationStep; i <= maxIterations * iterationStep; i += iterationStep) {
        List<String> stringValues = new LinkedList<String>();
        List<Double> doubleValues = new LinkedList<Double>();
        List<Date> dateValues = new LinkedList<Date>();

        txn = transactionService.getUserTransaction();
        long startCreate = System.currentTimeMillis();
        txn.begin();
        for (int j = 0; j < i; j++) {
            PropValGenerator valueGen = new PropValGenerator(propertyValueDAO);
            String stringValue = valueGen.createUniqueString();
            stringValues.add(stringValue);
            Double doubleValue = valueGen.createUniqueDouble();
            doubleValues.add(doubleValue);
            Date dateValue = valueGen.createUniqueDate();
            dateValues.add(dateValue);

            AuditQueryCallbackImpl preDeleteCallback = new AuditQueryCallbackImpl();
            AuditQueryCallbackImpl resultsCallback = new AuditQueryCallbackImpl();

            AuditApplicationInfo info1 = createAuditApp();
            String app1 = info1.getName();

            String username = "alexi";
            Map<String, Serializable> values = new HashMap<String, Serializable>();
            values.put("/a/b/string-" + j, stringValue);
            values.put("/a/b/double-" + j, doubleValue);
            values.put("/a/b/date-" + j, dateValue);
            // TODO: how to deal with Serializable values which cannot be retrieved later in test by value alone?
            long now = System.currentTimeMillis();
            auditDAO.createAuditEntry(info1.getId(), now, username, values);

            auditDAO.findAuditEntries(preDeleteCallback, new AuditQueryParameters(), Integer.MAX_VALUE);
            assertEquals(1, preDeleteCallback.numEntries(app1));

            // Delete audit entries between times - for all applications.
            auditDAO.deleteAuditEntries(info1.getId(), null, null);

            if (!performance) {
                auditDAO.findAuditEntries(resultsCallback, new AuditQueryParameters(), Integer.MAX_VALUE);
                assertEquals("All entries should have been deleted from app1", 0,
                        resultsCallback.numEntries(app1));
            }
        }
        txn.commit();
        System.out.println("Created values for " + i + " entries in "
                + (System.currentTimeMillis() - startCreate) + " ms.");

        if (!performance) {
            // Check there are some persisted values to delete.
            // Unlike PropertyValueDAOTest we're using the getPropertyValue() method here,
            // instead of the datatype-specific methods (e.g. getPropertyStringValue()).
            // This is because AuditDAO persists an entire map of values resulting in different behaviour
            // (i.e. dates are persisted as Serializable)
            for (String stringValue : stringValues) {
                assertEquals(stringValue, propertyValueDAO.getPropertyValue(stringValue).getSecond());
            }
            for (Double doubleValue : doubleValues) {
                assertEquals(doubleValue, propertyValueDAO.getPropertyValue(doubleValue).getSecond());
            }
            for (Date dateValue : dateValues) {
                assertEquals(dateValue, propertyValueDAO.getPropertyValue(dateValue).getSecond());
            }
        }
        long startDelete = System.currentTimeMillis();
        RetryingTransactionCallback<Void> callback = new RetryingTransactionCallback<Void>() {
            public Void execute() throws Throwable {
                propertyValueDAO.cleanupUnusedValues();

                return null;
            }
        };
        // use a new transaction so it will retry in that transaction
        txnHelper.doInTransaction(callback, false, true);

        System.out.println("Cleaned values for " + i + " entries in "
                + (System.currentTimeMillis() - startDelete) + " ms.");

        if (!performance) {
            // Check all the properties have been deleted.
            txn = transactionService.getUserTransaction();
            txn.begin();

            for (String stringValue : stringValues) {
                assertPropDeleted(propertyValueDAO.getPropertyValue(stringValue));
            }
            for (Double doubleValue : doubleValues) {
                assertPropDeleted(propertyValueDAO.getPropertyValue(doubleValue));
            }
            for (Date dateValue : dateValues) {
                assertPropDeleted(propertyValueDAO.getPropertyValue(dateValue));
            }

            txn.commit();
        }
    }
}

From source file:org.alfresco.repo.imap.ImapMessageTest.java

@Override
public void setUp() throws Exception {
    logger.debug("In SetUp");
    serviceRegistry = (ServiceRegistry) ctx.getBean("ServiceRegistry");
    transactionService = serviceRegistry.getTransactionService();
    nodeService = serviceRegistry.getNodeService();
    importerService = serviceRegistry.getImporterService();
    personService = serviceRegistry.getPersonService();
    authenticationService = serviceRegistry.getAuthenticationService();
    searchService = serviceRegistry.getSearchService();
    namespaceService = serviceRegistry.getNamespaceService();
    fileFolderService = serviceRegistry.getFileFolderService();

    // start the transaction
    UserTransaction txn = transactionService.getUserTransaction();
    txn.begin();
    authenticationService.authenticate(ADMIN_USER_NAME, ADMIN_USER_PASSWORD.toCharArray());

    // downgrade integrity
    IntegrityChecker.setWarnInTransaction();

    anotherUserName = "user" + System.currentTimeMillis();

    PropertyMap testUser = new PropertyMap();
    testUser.put(ContentModel.PROP_USERNAME, anotherUserName);
    testUser.put(ContentModel.PROP_FIRSTNAME, anotherUserName);
    testUser.put(ContentModel.PROP_LASTNAME, anotherUserName);
    testUser.put(ContentModel.PROP_EMAIL, anotherUserName + "@alfresco.com");
    testUser.put(ContentModel.PROP_JOBTITLE, "jobTitle");

    personService.createPerson(testUser);

    // create the ACEGI Authentication instance for the new user
    authenticationService.createAuthentication(anotherUserName, anotherUserName.toCharArray());

    StoreRef storeRef = new StoreRef(storePath);
    storeRootNodeRef = nodeService.getRootNode(storeRef);

    List<NodeRef> nodeRefs = searchService.selectNodes(storeRootNodeRef, companyHomePathInStore, null,
            namespaceService, false);/*from   w w  w.j  a v a 2 s. com*/
    NodeRef companyHomeNodeRef = nodeRefs.get(0);

    nodeRefs = searchService.selectNodes(storeRootNodeRef,
            companyHomePathInStore + "/" + NamespaceService.CONTENT_MODEL_PREFIX + ":" + IMAP_FOLDER_NAME, null,
            namespaceService, false);
    if (nodeRefs != null && nodeRefs.size() > 0) {
        fileFolderService.delete(nodeRefs.get(0));
    }

    ChildApplicationContextFactory imap = (ChildApplicationContextFactory) ctx.getBean("imap");
    ApplicationContext imapCtx = imap.getApplicationContext();
    ImapServiceImpl imapServiceImpl = (ImapServiceImpl) imapCtx.getBean("imapService");
    imapServer = (AlfrescoImapServer) imapCtx.getBean("imapServer");

    if (!imapServer.isImapServerEnabled()) {
        imapServer.setImapServerEnabled(true);
        imapServer.setHost(HOST);
        imapServer.setPort(PORT);
        imapServer.startup();
    }

    // Creating IMAP test folder for IMAP root
    LinkedList<String> folders = new LinkedList<String>();
    folders.add(IMAP_FOLDER_NAME);
    FileFolderUtil.makeFolders(fileFolderService, companyHomeNodeRef, folders, ContentModel.TYPE_FOLDER);

    // Setting IMAP root
    RepositoryFolderConfigBean imapHome = new RepositoryFolderConfigBean();
    imapHome.setStore(storePath);
    imapHome.setRootPath(companyHomePathInStore);
    imapHome.setFolderPath(NamespaceService.CONTENT_MODEL_PREFIX + ":" + IMAP_FOLDER_NAME);
    imapServiceImpl.setImapHome(imapHome);

    // Starting IMAP
    imapServiceImpl.startupInTxn(true);

    nodeRefs = searchService.selectNodes(storeRootNodeRef,
            companyHomePathInStore + "/" + NamespaceService.CONTENT_MODEL_PREFIX + ":" + IMAP_FOLDER_NAME, null,
            namespaceService, false);
    testImapFolderNodeRef = nodeRefs.get(0);

    /*
     * Importing test folders: Test folder contains: "___-___folder_a" "___-___folder_a" contains: "___-___folder_a_a", "___-___file_a", "Message_485.eml" (this is IMAP
     * Message) "___-___folder_a_a" contains: "____-____file_a_a"
     */
    importInternal("imap/imapservice_test_folder_a.acp", testImapFolderNodeRef);

    txn.commit();

    // Init mail client session
    Properties props = new Properties();
    props.setProperty("mail.imap.partialfetch", "false");
    this.session = Session.getDefaultInstance(props, null);

    // Get the store
    this.store = session.getStore(PROTOCOL);
    //this.store.connect(HOST, PORT, anotherUserName, anotherUserName);
    this.store.connect(imapServer.getHost(), imapServer.getPort(), anotherUserName, anotherUserName);

    // Get folder
    folder = (IMAPFolder) store.getFolder(TEST_FOLDER);
    folder.open(Folder.READ_ONLY);

    logger.debug("End SetUp");

}

From source file:org.alfresco.repo.imap.ImapMessageTest.java

public void testMessageModifiedBetweenReads() throws Exception {
    // Get test message UID
    final Long uid = getMessageUid(folder, 1);

    // Get unmodified message
    BODY body = getMessageBody(folder, uid);

    // Parse the multipart MIME message
    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()),
            new BufferedInputStream(body.getByteArrayInputStream()));

    // Reading first part - should be successful
    MimeMultipart content = (MimeMultipart) message.getContent();
    assertNotNull(content.getBodyPart(0).getContent());
    // Reading second part - should be successful
    assertNotNull(content.getBodyPart(1).getContent());

    // Modify message. The size of letter describing the node may 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();
    ContentWriter writer = fileFolderService.getWriter(contentNode);
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < 2000; i++) {
        sb.append("test string");
    }//from   w ww. ja v  a2  s . c  o m
    writer.putContent(sb.toString());
    txn.commit();

    // Read updated message part
    BODY bodyNew = getMessageBody(folder, uid);

    // The body should be updated
    assertFalse(Arrays.equals(bodyNew.getByteArray().getBytes(), body.getByteArray().getBytes()));

    // Parse the multipart MIME message
    message = new MimeMessage(Session.getDefaultInstance(new Properties()),
            new BufferedInputStream(bodyNew.getByteArrayInputStream()));

    // Reading first part - should be successful
    content = (MimeMultipart) message.getContent();
    assertNotNull(content.getBodyPart(0).getContent());
    // Reading second part - should be successful
    assertNotNull(content.getBodyPart(1).getContent());
}

From source file:org.alfresco.repo.imap.ImapMessageTest.java

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();/*from  w  ww  .  j  a v a  2  s  .c o  m*/

    // 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) {
    }
}

From source file:org.alfresco.repo.imap.ImapMessageTest.java

public void dontTestMessageCache() throws Exception {

    // Create messages
    NodeRef contentNode = findNode(companyHomePathInStore + TEST_FILE);
    UserTransaction txn = transactionService.getUserTransaction();
    txn.begin();

    // Create messages more than cache capacity
    for (int i = 0; i < 51; i++) {
        FileInfo fi = fileFolderService.create(nodeService.getParentAssocs(contentNode).get(0).getParentRef(),
                "test" + i, ContentModel.TYPE_CONTENT);
        ContentWriter writer = fileFolderService.getWriter(fi.getNodeRef());
        writer.putContent("test");
    }/*from w  ww. j a  v a2 s .co  m*/

    txn.commit();

    // Reload folder
    folder.close(false);
    folder = (IMAPFolder) store.getFolder(TEST_FOLDER);
    folder.open(Folder.READ_ONLY);

    // Read all messages
    for (int i = 1; i < 51; i++) {
        // Get test message UID
        final Long uid = getMessageUid(folder, i);
        // Get Message size
        final int count = getMessageSize(folder, uid);

        // Get first part
        BODY body = getMessageBodyPart(folder, uid, 0, count - 100);
        // Read second message part
        BODY bodyRest = getMessageBodyPart(folder, uid, count - 100, 100);

        // 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());
        assertNotNull(content.getBodyPart(1).getContent());
    }
}

From source file:org.alfresco.repo.imap.ImapMessageTest.java

@Override
public void tearDown() throws Exception {
    // Deleting created test environment
    logger.debug("tearDown ");

    UserTransaction txn = transactionService.getUserTransaction();
    txn.begin();

    List<NodeRef> nodeRefs = searchService.selectNodes(storeRootNodeRef,
            companyHomePathInStore + "/" + NamespaceService.CONTENT_MODEL_PREFIX + ":" + IMAP_FOLDER_NAME, null,
            namespaceService, false);//w w w . j a  v a 2s  . co m
    if (nodeRefs != null && nodeRefs.size() > 0) {
        fileFolderService.delete(nodeRefs.get(0));
    }

    authenticationService.deleteAuthentication(anotherUserName);
    personService.deletePerson(anotherUserName);

    txn.commit();

    // Closing client connection
    folder.close(false);
    store.close();
    logger.debug("tearDown end");
}