View Javadoc

1   /**
2    * Copyright 2005-2011 The Kuali Foundation
3    *
4    * Licensed under the Educational Community License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.opensource.org/licenses/ecl2.php
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.kuali.rice.ken.services.impl;
17  
18  import org.junit.Ignore;
19  import org.junit.Test;
20  import org.kuali.rice.core.framework.persistence.dao.GenericDao;
21  import org.kuali.rice.kcb.service.GlobalKCBServiceLocator;
22  import org.kuali.rice.kcb.service.MessageService;
23  import org.kuali.rice.ken.bo.NotificationBo;
24  import org.kuali.rice.ken.bo.NotificationMessageDelivery;
25  import org.kuali.rice.ken.service.NotificationMessageDeliveryResolverService;
26  import org.kuali.rice.ken.service.NotificationRecipientService;
27  import org.kuali.rice.ken.service.NotificationService;
28  import org.kuali.rice.ken.service.ProcessingResult;
29  import org.kuali.rice.ken.service.UserPreferenceService;
30  import org.kuali.rice.ken.service.impl.NotificationMessageDeliveryResolverServiceImpl;
31  import org.kuali.rice.ken.test.KENTestCase;
32  import org.kuali.rice.ken.util.NotificationConstants;
33  import org.kuali.rice.test.data.PerTestUnitTestData;
34  import org.kuali.rice.test.data.UnitTestData;
35  import org.kuali.rice.test.data.UnitTestSql;
36  import org.springframework.transaction.PlatformTransactionManager;
37  
38  import java.util.Collection;
39  import java.util.HashMap;
40  import java.util.concurrent.ExecutorService;
41  import java.util.concurrent.Executors;
42  
43  import static org.junit.Assert.*;
44  
45  //import org.kuali.rice.core.jpa.criteria.Criteria;
46  
47  /**
48   * Tests NotificationMessageDeliveryResolverServiceImpl
49   * @author Kuali Rice Team (rice.collab@kuali.org)
50   */
51  // deadlocks are detected during clear database lifecycle (even when select for update is commented out...)
52  // Make sure KCB has some deliverers configured for the test users, so message deliveries get created and the messages aren't removed
53  @PerTestUnitTestData(
54  		@UnitTestData(
55  				order = { UnitTestData.Type.SQL_STATEMENTS },
56  				sqlStatements = {
57  						@UnitTestSql("insert into KREN_RECIP_DELIV_T (RECIP_DELIV_ID, RECIP_ID, CHNL, NM, VER_NBR) values (1, 'testuser6', 'KEW', 'mock', 0)"),
58  						@UnitTestSql("insert into KREN_RECIP_DELIV_T (RECIP_DELIV_ID, RECIP_ID, CHNL, NM, VER_NBR) values (2, 'testuser1', 'KEW', 'mock', 0)"),
59  						@UnitTestSql("insert into KREN_RECIP_DELIV_T (RECIP_DELIV_ID, RECIP_ID, CHNL, NM, VER_NBR) values (3, 'testuser2', 'KEW', 'mock', 0)"),
60  						@UnitTestSql("insert into KREN_RECIP_DELIV_T (RECIP_DELIV_ID, RECIP_ID, CHNL, NM, VER_NBR) values (4, 'quickstart', 'KEW', 'mock', 0)"),
61  						@UnitTestSql("insert into KREN_RECIP_DELIV_T (RECIP_DELIV_ID, RECIP_ID, CHNL, NM, VER_NBR) values (5, 'testuser5', 'KEW', 'mock', 0)"),
62  						@UnitTestSql("insert into KREN_RECIP_DELIV_T (RECIP_DELIV_ID, RECIP_ID, CHNL, NM, VER_NBR) values (6, 'testuser4', 'KEW', 'mock', 0)")
63  				}
64  		)
65  )
66  @Ignore
67  public class NotificationMessageDeliveryResolverServiceImplTest extends KENTestCase {
68      // NOTE: this value is HIGHLY dependent on the test data, make sure that it reflects the results
69      // expected from the test data
70      private static final int EXPECTED_SUCCESSES = 6;
71  
72      /**
73       * Id of notification for which we will intentionally generate an exception during processing
74       */
75      private static final long BAD_NOTIFICATION_ID = 3L;
76  
77      private static class TestNotificationMessageDeliveryResolverService extends NotificationMessageDeliveryResolverServiceImpl {
78          public TestNotificationMessageDeliveryResolverService(NotificationService notificationService, NotificationRecipientService notificationRecipientService,
79                  GenericDao businessObjectDao, PlatformTransactionManager txManager, ExecutorService executor, UserPreferenceService userPreferenceService) {
80              super(notificationService, notificationRecipientService, businessObjectDao, txManager, executor, userPreferenceService);
81          }
82  
83          @Override
84          protected Collection<Object> processWorkItems(Collection<NotificationBo> notifications) {
85              for (NotificationBo notification: notifications) {
86                  if (notification.getId().longValue() == BAD_NOTIFICATION_ID) {
87                      throw new RuntimeException("Intentional heinous exception");
88                  }
89              }
90              return super.processWorkItems(notifications);
91          }
92      }
93  
94      protected TestNotificationMessageDeliveryResolverService getResolverService() {
95          return new TestNotificationMessageDeliveryResolverService(services.getNotificationService(), services.getNotificationRecipientService(), services.getGenericDao(), transactionManager,
96          	Executors.newFixedThreadPool(5), services.getUserPreferenceService());
97      }
98  
99      //this is the one need to tweek on Criteria
100     protected void assertProcessResults() {
101         // one error should have occurred and the delivery should have been marked unlocked again
102     	Collection<NotificationMessageDelivery> lockedDeliveries = services.getNotificationMessegDeliveryDao().getLockedDeliveries(NotificationBo.class, services.getGenericDao());
103          
104     	assertEquals(0, lockedDeliveries.size());
105 
106         // should be 1 unprocessed delivery (the one that had an error)
107         HashMap<String, String> queryCriteria = new HashMap<String, String>();
108         queryCriteria.put(NotificationConstants.BO_PROPERTY_NAMES.PROCESSING_FLAG, NotificationConstants.PROCESSING_FLAGS.UNRESOLVED);
109         Collection<NotificationBo> unprocessedDeliveries = services.getGenericDao().findMatching(NotificationBo.class, queryCriteria);
110         assertEquals(1, unprocessedDeliveries.size());
111         NotificationBo n = unprocessedDeliveries.iterator().next();
112         // #3 is the bad one
113         assertEquals(BAD_NOTIFICATION_ID, n.getId().longValue());
114     }
115 
116     /**
117      * Test resolution of notifications
118      * This test resolves UNRESOLVED notification ids #3 and #4 in the test data.  An artificial exception is generated for notification #3.
119      * For notification #4, the recipients are defined to be the Rice Team and testuser1.  This results in 8 recipient resolutions, two of which
120      * are Email deliveries for jaf30 and ag266.
121      * If you change the test data this test should be updated to reflect the expected results.
122      */
123     @Test
124     public void testResolveNotificationMessageDeliveries() throws Exception {
125         NotificationMessageDeliveryResolverService nSvc = getResolverService();
126 
127         ProcessingResult result = nSvc.resolveNotificationMessageDeliveries();
128 
129         Thread.sleep(20000);
130 
131         assertEquals(EXPECTED_SUCCESSES, result.getSuccesses().size());
132 
133         MessageService ms = (MessageService) GlobalKCBServiceLocator.getInstance().getMessageService();
134         assertEquals(result.getSuccesses().size(), ms.getAllMessages().size());
135 
136         assertProcessResults();
137     }
138 
139 
140     /**
141      * Test concurrent resolution of notifications
142      */
143     @Test
144     public void testResolverConcurrency() throws InterruptedException {
145         final NotificationMessageDeliveryResolverService nSvc = getResolverService();
146 
147         final ProcessingResult[] results = new ProcessingResult[2];
148         Thread t1 = new Thread(new Runnable() {
149             public void run() {
150                 try {
151                     results[0] = nSvc.resolveNotificationMessageDeliveries();
152                 } catch (Exception e) {
153                     System.err.println("Error resolving notification message deliveries");
154                     e.printStackTrace();
155                 }
156             }
157         });
158         Thread t2 = new Thread(new Runnable() {
159             public void run() {
160                 try {
161                     results[1] = nSvc.resolveNotificationMessageDeliveries();
162                 } catch (Exception e) {
163                     System.err.println("Error resolving notification message deliveries");
164                     e.printStackTrace();
165                 }
166             }
167         });
168 
169         t1.start();
170         t2.start();
171 
172         t1.join();
173         t2.join();
174 
175         // assert that ONE of the resolvers got all the items, and the other got NONE of the items
176         LOG.info("Results of thread #1: " + results[0]);
177         LOG.info("Results of thread #2: " + results[1]);
178         assertNotNull(results[0]);
179         assertNotNull(results[1]);
180         assertTrue((results[0].getSuccesses().size() == EXPECTED_SUCCESSES && results[0].getFailures().size() == 1 && results[1].getSuccesses().size() == 0 && results[1].getFailures().size() == 0) ||
181                    (results[1].getSuccesses().size() == EXPECTED_SUCCESSES && results[1].getFailures().size() == 1 && results[0].getSuccesses().size() == 0 && results[0].getFailures().size() == 0));
182 
183         assertProcessResults();
184     }
185 }