public Response addTest(@Context ServletContext context,
@PathParam("emailAddress") InternetAddress emailAddress,
@DefaultValue("true") @FormParam("sendTest") Boolean sendTest)
throws WebApplicationException {
UUID challenge = UUID.randomUUID();
DataManager dataManager = getDataManager();
try {
VerifiedAccount account = dataManager
.getVerifiedAccount(emailAddress);
Test newTest = dataManager.createTest(account, new Date(),
challenge);
if (sendTest) {
Session session = Session.getDefaultInstance(new Properties(),
null);
Message msg = null;
try {
InternetAddress appInternetAddress = new InternetAddress(
TestMessageConstants.TESTS_EMAIL_ADDRESS,
TestMessageConstants.TEST_MESSAGE_SENDER_NAME);
Map<String, Object> params = Maps.newHashMap();
params.put("challenge", newTest.getChallenge());
params.put(
"url",
"http://"
+ SystemProperty.applicationId.get()
+ ".appspot.com/answerTest.jsp?emailAddress="
+ account.getEmailAddress() + "&challenge="
+ newTest.getChallenge());
String content = TemplateManager.getInstance(context)
.applyTemplate(TemplateType.TEST_MESSAGE, params);
msg = new MimeMessage(session);
msg.setFrom(appInternetAddress);
msg.addRecipient(Message.RecipientType.TO,
account.getInternetAddress());
msg.setReplyTo(new InternetAddress[] { appInternetAddress });
msg.addHeader(
TestMessageConstants.SMTP_HEADER_ACCOUNT_IDENTIFIER,
KeyFactory.keyToString(account.getIdentifier()));
msg.addHeader(
TestMessageConstants.SMTP_HEADER_TEST_IDENTIFIER,
KeyFactory.keyToString(newTest.getIdentifier()));
msg.setSubject("Test Message on "
+ DateFormat.getInstance()
.format(newTest.getDate()));
msg.setContent(content, "text/plain");
Transport.send(msg);
} catch (Exception e) {
/*
* Remove the test that was not successfully sent
*/
dataManager.removeTest(newTest);
throw new WebApplicationException(
Response.serverError()
.entity("Error while sending the following test message to '"
+ account.getEmailAddress()
+ "': "
+ msg).entity(e).build());
}
}
URI newEntityURI = uriInfo.getBaseUri().resolve(
"/resources/accounts/" + emailAddress.getAddress()
+ "/tests/" + challenge);
return Response.created(newEntityURI).build();
} catch (UnknownVerifiedAccountException e) {
throw new WebApplicationException(Response
.status(Status.NOT_FOUND)
.entity("No account '" + emailAddress.getAddress()
+ "' found").build());
} finally {
dataManager.close();
}
}