Java Code Examples for org.springframework.mail.MailSendException

The following examples show how to use org.springframework.mail.MailSendException. These examples are extracted from open source projects. 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 Project: spring-analysis-note   Source File: JavaMailSenderTests.java    License: MIT License 6 votes vote down vote up
@Test
public void failedMailServerConnect() {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost(null);
	sender.setUsername("username");
	sender.setPassword("password");
	SimpleMailMessage simpleMessage1 = new SimpleMailMessage();
	try {
		sender.send(simpleMessage1);
		fail("Should have thrown MailSendException");
	}
	catch (MailSendException ex) {
		// expected
		ex.printStackTrace();
		assertTrue(ex.getFailedMessages() != null);
		assertEquals(1, ex.getFailedMessages().size());
		assertSame(simpleMessage1, ex.getFailedMessages().keySet().iterator().next());
		assertSame(ex.getCause(), ex.getFailedMessages().values().iterator().next());
	}
}
 
Example 2
Source Project: spring-analysis-note   Source File: JavaMailSenderTests.java    License: MIT License 6 votes vote down vote up
@Test
public void failedMailServerClose() {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost("");
	sender.setUsername("username");
	sender.setPassword("password");
	SimpleMailMessage simpleMessage1 = new SimpleMailMessage();
	try {
		sender.send(simpleMessage1);
		fail("Should have thrown MailSendException");
	}
	catch (MailSendException ex) {
		// expected
		ex.printStackTrace();
		assertTrue(ex.getFailedMessages() != null);
		assertEquals(0, ex.getFailedMessages().size());
	}
}
 
Example 3
Source Project: java-technology-stack   Source File: JavaMailSenderTests.java    License: MIT License 6 votes vote down vote up
@Test
public void failedMailServerConnect() {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost(null);
	sender.setUsername("username");
	sender.setPassword("password");
	SimpleMailMessage simpleMessage1 = new SimpleMailMessage();
	try {
		sender.send(simpleMessage1);
		fail("Should have thrown MailSendException");
	}
	catch (MailSendException ex) {
		// expected
		ex.printStackTrace();
		assertTrue(ex.getFailedMessages() != null);
		assertEquals(1, ex.getFailedMessages().size());
		assertSame(simpleMessage1, ex.getFailedMessages().keySet().iterator().next());
		assertSame(ex.getCause(), ex.getFailedMessages().values().iterator().next());
	}
}
 
Example 4
Source Project: java-technology-stack   Source File: JavaMailSenderTests.java    License: MIT License 6 votes vote down vote up
@Test
public void failedMailServerClose() {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost("");
	sender.setUsername("username");
	sender.setPassword("password");
	SimpleMailMessage simpleMessage1 = new SimpleMailMessage();
	try {
		sender.send(simpleMessage1);
		fail("Should have thrown MailSendException");
	}
	catch (MailSendException ex) {
		// expected
		ex.printStackTrace();
		assertTrue(ex.getFailedMessages() != null);
		assertEquals(0, ex.getFailedMessages().size());
	}
}
 
Example 5
Source Project: spring4-understanding   Source File: JavaMailSenderTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void failedMailServerConnect() throws Exception {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost(null);
	sender.setUsername("username");
	sender.setPassword("password");
	SimpleMailMessage simpleMessage1 = new SimpleMailMessage();
	try {
		sender.send(simpleMessage1);
		fail("Should have thrown MailSendException");
	}
	catch (MailSendException ex) {
		// expected
		ex.printStackTrace();
		assertTrue(ex.getFailedMessages() != null);
		assertEquals(1, ex.getFailedMessages().size());
		assertSame(simpleMessage1, ex.getFailedMessages().keySet().iterator().next());
		assertSame(ex.getCause(), ex.getFailedMessages().values().iterator().next());
	}
}
 
Example 6
Source Project: spring4-understanding   Source File: JavaMailSenderTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void failedMailServerClose() throws Exception {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost("");
	sender.setUsername("username");
	sender.setPassword("password");
	SimpleMailMessage simpleMessage1 = new SimpleMailMessage();
	try {
		sender.send(simpleMessage1);
		fail("Should have thrown MailSendException");
	}
	catch (MailSendException ex) {
		// expected
		ex.printStackTrace();
		assertTrue(ex.getFailedMessages() != null);
		assertEquals(0, ex.getFailedMessages().size());
	}
}
 
Example 7
Source Project: olat   Source File: TransactionRetryerITCaseNew.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@Ignore
// 18.04.2012/cg Hudson failed => LD or AA
// TODO: THIS METHOD HAS TO BE REMOVED; IT'S REPLACED WITH THE NEXT ONE
public void testNotifySubscribers_IfNotifyDelegateThrowsException_checkNumberOfRetriesForMailSendException() {

    Long subscriberId = new Long(1);
    NotifyDelegate mockNotifyDelegate = mock(NotifyDelegate.class);
    when(mockNotifyDelegate.notifySubscriber(subscriberId)).thenThrow(new MailSendException("mock exception"));
    notificationService.setNotifyDelegate(mockNotifyDelegate);

    try {
        verify(notificationService.notifySubscribers());
    } catch (Exception e) {
        System.out.println("catch to check for number of retries");
    }

    // the number of retries for MailSendException is configured via maxRetriesPerException bean property in lmsLearnTestContext.xml
    verify(mockNotifyDelegate, times(4)).notifySubscriber(subscriberId);
}
 
Example 8
Source Project: olat   Source File: TransactionRetryerITCaseNew.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@Ignore
// 18.04.2012/cg Hudson failed => LD or AA
// TODO: THIS METHOD HAS TO BE REMOVED; IT'S REPLACED WITH THE NEXT ONE
public void testNotifySubscribers_IfNotifyDelegateThrowsException_checkNumberOfRetriesForMailSendException() {

    Long subscriberId = new Long(1);
    NotifyDelegate mockNotifyDelegate = mock(NotifyDelegate.class);
    when(mockNotifyDelegate.notifySubscriber(subscriberId)).thenThrow(new MailSendException("mock exception"));
    notificationService.setNotifyDelegate(mockNotifyDelegate);

    try {
        verify(notificationService.notifySubscribers());
    } catch (Exception e) {
        System.out.println("catch to check for number of retries");
    }

    // the number of retries for MailSendException is configured via maxRetriesPerException bean property in lmsLearnTestContext.xml
    verify(mockNotifyDelegate, times(4)).notifySubscriber(subscriberId);
}
 
Example 9
Source Project: olat   Source File: NotificationServiceImplTest.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked" })
@Test
public void notifySubscribersFailed() {
    boolean finished = true;
    List<NotificationServiceMetric<NotificationServiceContext>> metrics = new ArrayList<NotificationServiceMetric<NotificationServiceContext>>();
    NotificationServiceMetric<? extends NotificationServiceContext> notifySuccessMetric = new AverageEmailSuccessRateMetric();
    metrics.add((NotificationServiceMetric<NotificationServiceContext>) notifySuccessMetric);
    notificationServiceImpl.setMetrics(metrics);
    when(notificationServiceImpl.notifyDelegate.notifySubscriber(any(Long.class))).thenThrow(new MailSendException("mock exception"));
    try {
        notificationServiceImpl.startNotificationJob();
        notificationServiceImpl.notifySubscriber(Long.valueOf(1));
        notificationServiceImpl.finishNotificationJob();
    } catch (MailSendException e) {

        for (NotificationServiceMetric<?> metric : metrics) {
            if (metric instanceof AverageEmailSuccessRateMetric) {
                finished = ((AverageEmailSuccessRateMetric) metric).isJobFinishedOrNotStartedYet();
            }
        }
    }
    assertTrue(finished == false);
}
 
Example 10
@SuppressWarnings("OverloadedVarargsMethod")
@Override
public void send(SimpleMailMessage... simpleMailMessages) throws MailException {

	Map<Object, Exception> failedMessages = new HashMap<>();

	for (SimpleMailMessage simpleMessage : simpleMailMessages) {
		try {
			SendEmailResult sendEmailResult = getEmailService()
					.sendEmail(prepareMessage(simpleMessage));
			if (LOGGER.isDebugEnabled()) {
				LOGGER.debug("Message with id: {} successfully send",
						sendEmailResult.getMessageId());
			}
		}
		catch (AmazonClientException e) {
			// Ignore Exception because we are collecting and throwing all if any
			// noinspection ThrowableResultOfMethodCallIgnored
			failedMessages.put(simpleMessage, e);
		}
	}

	if (!failedMessages.isEmpty()) {
		throw new MailSendException(failedMessages);
	}
}
 
Example 11
@Test
void testSendMultipleMailsWithExceptionWhileSending() throws Exception {
	AmazonSimpleEmailService emailService = mock(AmazonSimpleEmailService.class);
	SimpleEmailServiceMailSender mailSender = new SimpleEmailServiceMailSender(
			emailService);

	SimpleMailMessage firstMessage = createSimpleMailMessage();
	firstMessage.setBcc("[email protected]");

	SimpleMailMessage failureMail = createSimpleMailMessage();
	when(emailService.sendEmail(ArgumentMatchers.isA(SendEmailRequest.class)))
			.thenReturn(new SendEmailResult())
			.thenThrow(new AmazonClientException("error"))
			.thenReturn(new SendEmailResult());

	SimpleMailMessage thirdMessage = createSimpleMailMessage();

	try {
		mailSender.send(firstMessage, failureMail, thirdMessage);
		fail("Exception expected due to error while sending mail");
	}
	catch (MailSendException e) {
		assertThat(e.getFailedMessages().size()).isEqualTo(1);
		assertThat(e.getFailedMessages().containsKey(failureMail)).isTrue();
	}
}
 
Example 12
@SuppressWarnings("deprecation")
@Test
void createUserMailSendFailed()
    throws UsernameAlreadyExistsException, EmailAlreadyExistsException {

  when(idGenerator.generateId(SECURE_RANDOM)).thenReturn("3541db68-435b-416b-8c2c-cf2edf6ba435");
  doThrow(new MailSendException("mail send failed"))
      .when(mailSender)
      .send(any(SimpleMailMessage.class));

  Exception exception =
      assertThrows(
          MolgenisUserException.class,
          () -> accountService.createUser(user, "http://molgenis.org/activate"));
  assertThat(exception.getMessage())
      .containsPattern(
          "An error occurred. Please contact the administrator. You are not signed up!");
}
 
Example 13
Source Project: spring-analysis-note   Source File: JavaMailSenderTests.java    License: MIT License 5 votes vote down vote up
@Test
public void failedSimpleMessage() throws MessagingException {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost("host");
	sender.setUsername("username");
	sender.setPassword("password");

	SimpleMailMessage simpleMessage1 = new SimpleMailMessage();
	simpleMessage1.setTo("[email protected]");
	simpleMessage1.setSubject("fail");
	SimpleMailMessage simpleMessage2 = new SimpleMailMessage();
	simpleMessage2.setTo("[email protected]");

	try {
		sender.send(simpleMessage1, simpleMessage2);
	}
	catch (MailSendException ex) {
		ex.printStackTrace();
		assertEquals("host", sender.transport.getConnectedHost());
		assertEquals("username", sender.transport.getConnectedUsername());
		assertEquals("password", sender.transport.getConnectedPassword());
		assertTrue(sender.transport.isCloseCalled());
		assertEquals(1, sender.transport.getSentMessages().size());
		assertEquals(new InternetAddress("[email protected]"), sender.transport.getSentMessage(0).getAllRecipients()[0]);
		assertEquals(1, ex.getFailedMessages().size());
		assertEquals(simpleMessage1, ex.getFailedMessages().keySet().iterator().next());
		Object subEx = ex.getFailedMessages().values().iterator().next();
		assertTrue(subEx instanceof MessagingException);
		assertEquals("failed", ((MessagingException) subEx).getMessage());
	}
}
 
Example 14
Source Project: spring-analysis-note   Source File: JavaMailSenderTests.java    License: MIT License 5 votes vote down vote up
@Test
public void failedMimeMessage() throws MessagingException {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost("host");
	sender.setUsername("username");
	sender.setPassword("password");

	MimeMessage mimeMessage1 = sender.createMimeMessage();
	mimeMessage1.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
	mimeMessage1.setSubject("fail");
	MimeMessage mimeMessage2 = sender.createMimeMessage();
	mimeMessage2.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));

	try {
		sender.send(mimeMessage1, mimeMessage2);
	}
	catch (MailSendException ex) {
		ex.printStackTrace();
		assertEquals("host", sender.transport.getConnectedHost());
		assertEquals("username", sender.transport.getConnectedUsername());
		assertEquals("password", sender.transport.getConnectedPassword());
		assertTrue(sender.transport.isCloseCalled());
		assertEquals(1, sender.transport.getSentMessages().size());
		assertEquals(mimeMessage2, sender.transport.getSentMessage(0));
		assertEquals(1, ex.getFailedMessages().size());
		assertEquals(mimeMessage1, ex.getFailedMessages().keySet().iterator().next());
		Object subEx = ex.getFailedMessages().values().iterator().next();
		assertTrue(subEx instanceof MessagingException);
		assertEquals("failed", ((MessagingException) subEx).getMessage());
	}
}
 
Example 15
Source Project: seppb   Source File: FileServiceImpl.java    License: MIT License 5 votes vote down vote up
@Override
public void sendAttachMail(TestMail testMail) {
    User user = userDAO.findUserByUserId(ParameterThreadLocal.getUserId());
    String body = testMail.getBody().concat(String.format(EMAIL_FOOTER, user.getUserName(), user.getUserEmail()));
    MailDTO mailDTO;
    if (!isEmpty(testMail.getCc())) {
        mailDTO = MailDTO.builder().from(fromEmail)
                .to(testMail.getTo())
                .tocc(testMail.getCc())
                .content(body)
                .isHtml(true)
                .subject(testMail.getSubject())
                .build();
    } else {
        mailDTO = MailDTO.builder().from(fromEmail)
                .to(testMail.getTo())
                .content(body)
                .isHtml(true)
                .subject(testMail.getSubject())
                .build();
    }
    try {
        JavaMailUtils.sendMail(mailDTO);
    } catch (MailSendException ne) {
        if (ne.getMessage().indexOf("550 User not found") > 0) {
            log.error("邮件地址不存在", ne.getMessage());
        } else {
            throw new SeppServerException("邮件发送失败,请重试", ne);
        }
    } catch (Exception e) {
        throw new SeppServerException("邮件发送失败,请重试", e);
    }
}
 
Example 16
Source Project: java-technology-stack   Source File: JavaMailSenderTests.java    License: MIT License 5 votes vote down vote up
@Test
public void failedSimpleMessage() throws MessagingException {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost("host");
	sender.setUsername("username");
	sender.setPassword("password");

	SimpleMailMessage simpleMessage1 = new SimpleMailMessage();
	simpleMessage1.setTo("[email protected]");
	simpleMessage1.setSubject("fail");
	SimpleMailMessage simpleMessage2 = new SimpleMailMessage();
	simpleMessage2.setTo("[email protected]");

	try {
		sender.send(simpleMessage1, simpleMessage2);
	}
	catch (MailSendException ex) {
		ex.printStackTrace();
		assertEquals("host", sender.transport.getConnectedHost());
		assertEquals("username", sender.transport.getConnectedUsername());
		assertEquals("password", sender.transport.getConnectedPassword());
		assertTrue(sender.transport.isCloseCalled());
		assertEquals(1, sender.transport.getSentMessages().size());
		assertEquals(new InternetAddress("[email protected]"), sender.transport.getSentMessage(0).getAllRecipients()[0]);
		assertEquals(1, ex.getFailedMessages().size());
		assertEquals(simpleMessage1, ex.getFailedMessages().keySet().iterator().next());
		Object subEx = ex.getFailedMessages().values().iterator().next();
		assertTrue(subEx instanceof MessagingException);
		assertEquals("failed", ((MessagingException) subEx).getMessage());
	}
}
 
Example 17
Source Project: java-technology-stack   Source File: JavaMailSenderTests.java    License: MIT License 5 votes vote down vote up
@Test
public void failedMimeMessage() throws MessagingException {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost("host");
	sender.setUsername("username");
	sender.setPassword("password");

	MimeMessage mimeMessage1 = sender.createMimeMessage();
	mimeMessage1.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
	mimeMessage1.setSubject("fail");
	MimeMessage mimeMessage2 = sender.createMimeMessage();
	mimeMessage2.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));

	try {
		sender.send(mimeMessage1, mimeMessage2);
	}
	catch (MailSendException ex) {
		ex.printStackTrace();
		assertEquals("host", sender.transport.getConnectedHost());
		assertEquals("username", sender.transport.getConnectedUsername());
		assertEquals("password", sender.transport.getConnectedPassword());
		assertTrue(sender.transport.isCloseCalled());
		assertEquals(1, sender.transport.getSentMessages().size());
		assertEquals(mimeMessage2, sender.transport.getSentMessage(0));
		assertEquals(1, ex.getFailedMessages().size());
		assertEquals(mimeMessage1, ex.getFailedMessages().keySet().iterator().next());
		Object subEx = ex.getFailedMessages().values().iterator().next();
		assertTrue(subEx instanceof MessagingException);
		assertEquals("failed", ((MessagingException) subEx).getMessage());
	}
}
 
Example 18
Source Project: jhipster-online   Source File: MailServiceIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSendEmailWithException() {
    doThrow(MailSendException.class).when(javaMailSender).send(any(MimeMessage.class));
    try {
        mailService.sendEmail("[email protected]", "testSubject", "testContent", false, false);
    } catch (Exception e) {
        fail("Exception shouldn't have been thrown");
    }
}
 
Example 19
Source Project: QuizZz   Source File: TokenDeliverySystemEmailTests.java    License: MIT License 5 votes vote down vote up
@Test
public void failToSendEmailRegistrationToken_shouldNotThrowException() {
	String registrationConfigUri = String.format(CONFIG_URI, TokenType.REGISTRATION_MAIL.toString().toLowerCase());
	doReturn(TOKEN).when(token).getToken();
	doThrow(new MailSendException("")).when(mailServer).send((SimpleMailMessage) any());

	doReturn("dummyUrl/%1$d/%2$s").when(messageSource).getMessage(registrationConfigUri + ".url", null, null);
	doReturn("Subject").when(messageSource).getMessage(registrationConfigUri + ".subject", null, null);
	doReturn("Body %1$s %2$s").when(messageSource).getMessage(registrationConfigUri + ".body", null, null);

	tokenDeliverySystem.sendTokenToUser(token, user, TokenType.REGISTRATION_MAIL);
}
 
Example 20
Source Project: spring4-understanding   Source File: JavaMailSenderTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void failedSimpleMessage() throws Exception {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost("host");
	sender.setUsername("username");
	sender.setPassword("password");

	SimpleMailMessage simpleMessage1 = new SimpleMailMessage();
	simpleMessage1.setTo("[email protected]");
	simpleMessage1.setSubject("fail");
	SimpleMailMessage simpleMessage2 = new SimpleMailMessage();
	simpleMessage2.setTo("[email protected]");

	try {
		sender.send(simpleMessage1, simpleMessage2);
	}
	catch (MailSendException ex) {
		ex.printStackTrace();
		assertEquals("host", sender.transport.getConnectedHost());
		assertEquals("username", sender.transport.getConnectedUsername());
		assertEquals("password", sender.transport.getConnectedPassword());
		assertTrue(sender.transport.isCloseCalled());
		assertEquals(1, sender.transport.getSentMessages().size());
		assertEquals(new InternetAddress("[email protected]"), sender.transport.getSentMessage(0).getAllRecipients()[0]);
		assertEquals(1, ex.getFailedMessages().size());
		assertEquals(simpleMessage1, ex.getFailedMessages().keySet().iterator().next());
		Object subEx = ex.getFailedMessages().values().iterator().next();
		assertTrue(subEx instanceof MessagingException);
		assertEquals("failed", ((MessagingException) subEx).getMessage());
	}
}
 
Example 21
Source Project: spring4-understanding   Source File: JavaMailSenderTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void fFailedMimeMessage() throws Exception {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost("host");
	sender.setUsername("username");
	sender.setPassword("password");

	MimeMessage mimeMessage1 = sender.createMimeMessage();
	mimeMessage1.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
	mimeMessage1.setSubject("fail");
	MimeMessage mimeMessage2 = sender.createMimeMessage();
	mimeMessage2.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));

	try {
		sender.send(mimeMessage1, mimeMessage2);
	}
	catch (MailSendException ex) {
		ex.printStackTrace();
		assertEquals("host", sender.transport.getConnectedHost());
		assertEquals("username", sender.transport.getConnectedUsername());
		assertEquals("password", sender.transport.getConnectedPassword());
		assertTrue(sender.transport.isCloseCalled());
		assertEquals(1, sender.transport.getSentMessages().size());
		assertEquals(mimeMessage2, sender.transport.getSentMessage(0));
		assertEquals(1, ex.getFailedMessages().size());
		assertEquals(mimeMessage1, ex.getFailedMessages().keySet().iterator().next());
		Object subEx = ex.getFailedMessages().values().iterator().next();
		assertTrue(subEx instanceof MessagingException);
		assertEquals("failed", ((MessagingException) subEx).getMessage());
	}
}
 
Example 22
Source Project: cuba   Source File: TestMailSender.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void send(MimeMessage mimeMessage) throws MailException {
    if (mustFail) {
        throw new MailSendException("Smtp server not available");
    }
    myMessages.add(mimeMessage);
}
 
Example 23
Source Project: cuba   Source File: Emailer.java    License: Apache License 2.0 5 votes vote down vote up
protected boolean isNeedToRetry(Exception e) {
    if (e instanceof MailSendException) {
        if (e.getCause() instanceof SMTPAddressFailedException) {
            return false;
        }
    } else if (e instanceof AddressException) {
        return false;
    }
    return true;
}
 
Example 24
Source Project: olat   Source File: TransactionRetryerITCaseNew.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSend_IfMailServiceThrowsException_checkNumberOfRetriesForMailSendException() throws Exception {
    List<NotificationEventTO> eventTOs = new ArrayList<NotificationEventTO>();
    // Test Subscriber
    Subscriber subscriber = new Subscriber();
    subscriber.setIdentity(ObjectMother.createIdentity("testUser"));

    // Mock for TemplateMailTO
    TemplateMailTO templateMailTO = mock(TemplateMailTO.class);

    // Mock for EmailBuilder
    EmailBuilder emailBuilderMock = mock(EmailBuilder.class);
    when(emailBuilderMock.getTemplateMailTO(subscriber.getIdentity().getAttributes().getEmail(), eventTOs)).thenReturn(templateMailTO);
    mailChannel.setEmailBuilder(emailBuilderMock);

    // Mock for MailService
    MailService mailServiceMock = mock(MailService.class);
    doThrow(new MailSendException("MailService: Test Exception")).when(mailServiceMock).sendMailWithTemplate(templateMailTO);
    mailChannel.setMailService(mailServiceMock);

    try {
        mailChannel.send(subscriber, eventTOs);
    } catch (Exception e) {
        System.out.println("catch to check for number of retries");
    }

    verify(mailServiceMock, times(4)).sendMailWithTemplate(templateMailTO);
}
 
Example 25
Source Project: olat   Source File: TransactionRetryerITCaseNew.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Assumes that ConstraintViolationException could be retried once while MailSendException could be retried 3 times, see lmsLearnTestContext.xml for
 * maxRetriesPerException.
 */
@Test
public void isRetryStillAllowed_twoExceptionTypes_moreRetriesAllowed() {
    Map<String, Long> retriesPerException = new HashMap<String, Long>();
    assertTrue(transactionRetryer.isRetryStillAllowed(retriesPerException));

    // retry for ConstraintViolationException
    transactionRetryer.addOrIncrementRetries(retriesPerException, ConstraintViolationException.class.getName());
    assertTrue(transactionRetryer.isRetryStillAllowed(retriesPerException));

    for (int i = 0; i < 3; i++) {
        // retry for MailSendException
        transactionRetryer.addOrIncrementRetries(retriesPerException, MailSendException.class.getName());
        assertTrue(transactionRetryer.isRetryStillAllowed(retriesPerException));
    }

    // retry for MailSendException - isRetryStillAllowed should return false since MailSendException is configured to be retried 3 times
    transactionRetryer.addOrIncrementRetries(retriesPerException, MailSendException.class.getName());
    boolean isMailSendExceptionRetryAllowed = transactionRetryer.isRetryStillAllowed(retriesPerException);

    // retry second time no more allowed - throw error further
    transactionRetryer.addOrIncrementRetries(retriesPerException, ConstraintViolationException.class.getName());
    boolean isConstraintViolationExceptionAllowed = transactionRetryer.isRetryStillAllowed(retriesPerException);

    assertFalse(isMailSendExceptionRetryAllowed);
    assertFalse(isConstraintViolationExceptionAllowed);

    // retry no more allowed
    transactionRetryer.addOrIncrementRetries(retriesPerException, ConstraintViolationException.class.getName());
    assertFalse(transactionRetryer.isRetryStillAllowed(retriesPerException));
}
 
Example 26
Source Project: olat   Source File: ChannelChainTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void send_UserIsConfiguredForMailChannelOnly_Failed() throws Exception {
    subscriber.getChannels().remove(null);
    doThrow(new MailSendException("")).when(mailChannelMock).send(any(Subscriber.class), anyListOf(NotificationEventTO.class));
    NotifyStatistics statistics = channelChainTestObject.send(subscriber, eventTOs);
    assertEquals("Wrong number of the size", 1, statistics.getChannel2StatusMap().size());
    assertFalse(statistics.getChannel2StatusMap().get(Subscriber.Channel.EMAIL));
}
 
Example 27
Source Project: olat   Source File: ChannelChainTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void send_UserIsConfiguredForMailChannelAndDummyChannel_FailedForBoth() throws Exception {
    doThrow(new MailSendException("")).when(mailChannelMock).send(any(Subscriber.class), anyListOf(NotificationEventTO.class));
    doThrow(new MailSendException("")).when(dummyChannelMock).send(any(Subscriber.class), anyListOf(NotificationEventTO.class));
    NotifyStatistics statistics = channelChainTestObject.send(subscriber, eventTOs);
    assertEquals("Wrong number of the size", 2, statistics.getChannel2StatusMap().size());
    assertFalse(statistics.getChannel2StatusMap().get(Subscriber.Channel.EMAIL));
    assertFalse(statistics.getChannel2StatusMap().get(null));
}
 
Example 28
Source Project: olat   Source File: ChannelChainTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void send_UserIsConfiguredForMailChannelAndDummyChannel_SucessForMail_FaildForDummy() throws Exception {
    doNothing().when(mailChannelMock).send(any(Subscriber.class), anyListOf(NotificationEventTO.class));
    doThrow(new MailSendException("")).when(dummyChannelMock).send(any(Subscriber.class), anyListOf(NotificationEventTO.class));
    NotifyStatistics statistics = channelChainTestObject.send(subscriber, eventTOs);
    assertEquals("Wrong number of the size", 2, statistics.getChannel2StatusMap().size());
    assertTrue(statistics.getChannel2StatusMap().get(Subscriber.Channel.EMAIL));
    assertFalse(statistics.getChannel2StatusMap().get(null));
}
 
Example 29
Source Project: olat   Source File: ChannelChainTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void send_UserIsConfiguredForMailChannelAndDummyChannel_SucessForDummy_FaildForMail() throws Exception {
    doNothing().when(dummyChannelMock).send(any(Subscriber.class), anyListOf(NotificationEventTO.class));
    doThrow(new MailSendException("")).when(mailChannelMock).send(any(Subscriber.class), anyListOf(NotificationEventTO.class));
    NotifyStatistics statistics = channelChainTestObject.send(subscriber, eventTOs);
    assertEquals("Wrong number of the size", 2, statistics.getChannel2StatusMap().size());
    assertFalse(statistics.getChannel2StatusMap().get(Subscriber.Channel.EMAIL));
    assertTrue(statistics.getChannel2StatusMap().get(null));
}
 
Example 30
Source Project: olat   Source File: TransactionRetryerITCaseNew.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSend_IfMailServiceThrowsException_checkNumberOfRetriesForMailSendException() throws Exception {
    List<NotificationEventTO> eventTOs = new ArrayList<NotificationEventTO>();
    // Test Subscriber
    Subscriber subscriber = new Subscriber();
    subscriber.setIdentity(ObjectMother.createIdentity("testUser"));

    // Mock for TemplateMailTO
    TemplateMailTO templateMailTO = mock(TemplateMailTO.class);

    // Mock for EmailBuilder
    EmailBuilder emailBuilderMock = mock(EmailBuilder.class);
    when(emailBuilderMock.getTemplateMailTO(subscriber.getIdentity().getAttributes().getEmail(), eventTOs)).thenReturn(templateMailTO);
    mailChannel.setEmailBuilder(emailBuilderMock);

    // Mock for MailService
    MailService mailServiceMock = mock(MailService.class);
    doThrow(new MailSendException("MailService: Test Exception")).when(mailServiceMock).sendMailWithTemplate(templateMailTO);
    mailChannel.setMailService(mailServiceMock);

    try {
        mailChannel.send(subscriber, eventTOs);
    } catch (Exception e) {
        System.out.println("catch to check for number of retries");
    }

    verify(mailServiceMock, times(4)).sendMailWithTemplate(templateMailTO);
}