Changes for adding ability to email all users

This commit is contained in:
hjk54 2010-02-22 16:32:47 +00:00
parent 1afb527408
commit cbfe1940a6
9 changed files with 490 additions and 1 deletions

View file

@ -175,7 +175,6 @@ public class EntityController extends VitroHttpServlet {
} else {
log.debug("Found view parameter "+view+" in request for rendering "+entity.getName());
}
//set title before we do the highlighting so we don't get markup in it.
vreq.setAttribute("title",entity.getName());
//setup highlighter for search terms

View file

@ -0,0 +1,285 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.controller;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;
import edu.cornell.mannlib.vitro.webapp.ConfigurationProperties;
import edu.cornell.mannlib.vitro.webapp.beans.Portal;
import edu.cornell.mannlib.vitro.webapp.dao.UserDao;
public class MailUsersServlet extends VitroHttpServlet {
//private static final Logger LOG = Logger.getLogger(ContactMailServlet.class);
public static HttpServletRequest request;
public static HttpServletRequest response;
private static String smtpHost = null;
// private static final Log log = LogFactory.getLog(ContactMailServlet.class.getName());
public void init(ServletConfig servletConfig) throws javax.servlet.ServletException {
super.init(servletConfig);
smtpHost = getSmtpHostFromProperties();
}
public static boolean isSmtpHostConfigured() {
if( smtpHost==null || smtpHost.equals("")) {
return false;
}
return true;
}
private String getSmtpHostFromProperties() {
String host = ConfigurationProperties.getProperty("Vitro.smtpHost");
if (host != null && !host.equals("")) {
System.out.println("Found Vitro.smtpHost value is " + host);
//LOG.info("Found Vitro.smtpHost value of " + host);
} else {
System.out.println("No Vitro.smtpHost specified");
}
return (host != null && host.length() > 0) ? host : null;
}
public void doGet( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException {
VitroRequest vreq = new VitroRequest(request);
Portal portal = vreq.getPortal();
String confirmpage = "/thankyou.jsp";
String errpage = "/contact_err.jsp";
String status = null; // holds the error status
if (smtpHost==null || smtpHost.equals("")){
status = "This application has not yet been configured to send mail " +
"-- smtp host has not been identified in the Configuration Properties file.";
System.out.println("Status incorrect - would redirect otherwise");
//response.sendRedirect( "test?bodyJsp=" + errpage + "&ERR=" + status + "&home=" + portal.getPortalId() );
//return;
}
String SPAM_MESSAGE = "Your message was flagged as spam.";
boolean probablySpam = false;
String spamReason = "";
String originalReferer = (String) request.getSession().getAttribute("commentsFormReferer");
request.getSession().removeAttribute("commentsFormReferer");
if (originalReferer == null) {
originalReferer = "none";
// (the following does not support cookie-less browsing:)
// probablySpam = true;
// status = SPAM_MESSAGE;
} else {
String referer = request.getHeader("Referer");
//Review how spam works?
/*if (referer.indexOf("comments")<0 && referer.indexOf("correction")<0) {
probablySpam=true;
status = SPAM_MESSAGE ;
spamReason = "The form was not submitted from the Contact Us or Corrections page.";
}*/
}
String formType = vreq.getParameter("DeliveryType");
List<String> deliverToArray = null;
int recipientCount = 0;
String deliveryfrom = null;
deliveryfrom = "hjk54@cornell.edu"; //Who would this message be delivered from?
//Place-holder delivery To Array
/*deliverToArray = new String[] {
"huda.khan@gmail.com",
"huda.khan@colorado.edu",
"hjk54@cornell.edu",
"huda_jalil_khan@hotmail.com"
};*/
UserDao uDao = getWebappDaoFactory().getUserDao();
// get Individuals that the User mayEditAs
deliverToArray = uDao.getUserAccountEmails();
//Removed all form type stuff b/c recipients pre-configured
recipientCount=(deliverToArray == null) ? 0 : deliverToArray.size();
if (recipientCount == 0) {
//log.error("recipientCount is 0 when DeliveryType specified as \""+formType+"\"");
throw new Error(
"To establish the Contact Us mail capability the system administrators must "
+ "specify at least one email address in the current portal.");
}
// obtain passed in form data with a simple trim on the values
String webusername = vreq.getParameter("webusername");// Null.trim(); will give you an exception
String webuseremail = vreq.getParameter("webuseremail");//.trim();
String comments = vreq.getParameter("s34gfd88p9x1"); //what does this string signify?
webusername = "hjk54";
webuseremail = "hjk54@cornell.edu";
//comments = "following are comments";
webusername=webusername.trim();
comments=comments.trim();
//Removed spam filtering code
StringBuffer msgBuf = new StringBuffer(); // contains the intro copy for the body of the email message
String lineSeparator = System.getProperty("line.separator"); // \r\n on windows, \n on unix
// from MyLibrary
msgBuf.setLength(0);
msgBuf.append("Content-Type: text/html; charset='us-ascii'" + lineSeparator);
msgBuf.append("<html>" + lineSeparator );
msgBuf.append("<head>" + lineSeparator );
msgBuf.append("<style>a {text-decoration: none}</style>" + lineSeparator );
msgBuf.append("<title>" + deliveryfrom + "</title>" + lineSeparator );
msgBuf.append("</head>" + lineSeparator );
msgBuf.append("<body>" + lineSeparator );
msgBuf.append("<h4>" + deliveryfrom + "</h4>" + lineSeparator );
msgBuf.append("<h4>From: "+webusername +" (" + webuseremail + ")"+" at IP address "+request.getRemoteAddr()+"</h4>"+lineSeparator);
if (!(originalReferer == null || originalReferer.equals("none"))){
//The spam filter that is being used by the listsrv is rejecting <a href="...
//so try with out the markup, if that sill doesn't work,
//uncomment the following line to strip the http://
//msgBuf.append("<p><i>likely viewing page " + stripProtocol(originalReferer) );
msgBuf.append("<p><i>likely viewing page " + originalReferer );
}
msgBuf.append(lineSeparator + "</i></p><h3>Comments:</h3>" + lineSeparator );
if (comments==null || comments.equals("")) {
msgBuf.append("<p>BLANK MESSAGE</p>");
} else {
msgBuf.append("<p>"+comments+"</p>");
}
msgBuf.append("</body>" + lineSeparator );
msgBuf.append("</html>" + lineSeparator );
String msgText = msgBuf.toString();
// debugging
//PrintWriter outFile = new PrintWriter (new FileWriter(request.getSession().getServletContext().getRealPath("/WEB-INF/LatestMessage.html"),true)); //autoflush
Calendar cal = Calendar.getInstance();
/* outFile.println("<hr/>");
outFile.println();
outFile.println("<p>"+cal.getTime()+"</p>");
outFile.println();
if (probablySpam) {
outFile.println("<p>REJECTED - SPAM</p>");
outFile.println("<p>"+spamReason+"</p>");
outFile.println();
}
outFile.print( msgText );
outFile.println();
outFile.println();
outFile.flush();
// outFile.close();
*/
// Set the smtp host
Properties props = System.getProperties();
props.put("mail.smtp.host", smtpHost);
Session s = Session.getDefaultInstance(props,null); // was Session.getInstance(props,null);
//s.setDebug(true);
try {
// Construct the message
MimeMessage msg = new MimeMessage( s );
//System.out.println("trying to send message from servlet");
// Set the from address
msg.setFrom( new InternetAddress( webuseremail ));
// Set the recipient address
if (recipientCount>0){
InternetAddress[] address=new InternetAddress[recipientCount];
for (int i=0; i<recipientCount; i++){
address[i] = new InternetAddress(deliverToArray.get(i));
}
msg.setRecipients( Message.RecipientType.TO, address );
}
// Set the subject and text
msg.setSubject( deliveryfrom );
// add the multipart to the message
msg.setContent(msgText,"text/html");
// set the Date: header
msg.setSentDate( new Date() );
//System.out.println("sending from servlet");
//if (!probablySpam)
Transport.send( msg ); // try to send the message via smtp - catch error exceptions
} catch (AddressException e) {
status = "Please supply a valid email address.";
System.out.println("Error - status is " + status);
//outFile.println( status );
//outFile.println( e.getMessage() );
} catch (SendFailedException e) {
status = "The system was unable to deliver your mail. Please try again later. [SEND FAILED]";
System.out.println("Error - status is " + status);
//outFile.println( status );
//outFile.println( e.getMessage() );
} catch (MessagingException e) {
status = "The system was unable to deliver your mail. Please try again later. [MESSAGING]";
System.out.println("Error - status is " + status);
//outFile.println( status );
//outFile.println( e.getMessage() );
e.printStackTrace();
}
//outFile.flush();
//outFile.close();
// Redirect to the appropriate confirmation page
if (status == null && !probablySpam) {
// message was sent successfully
response.sendRedirect( "test?bodyJsp=" + confirmpage + "&home=" + portal.getPortalId() );
} else {
// exception occurred
response.sendRedirect( "test?bodyJsp=" + errpage + "&ERR=" + status + "&home=" + portal.getPortalId() );
}
}
public void doPost( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
doGet( request, response );
}
/** Intended to mangle url so it can get through spam filtering
* http://host/dir/servlet?param=value -> host: dir/servlet?param=value */
public String stripProtocol( String in ){
if( in == null )
return "";
else
return in.replaceAll("http://", "host: " );
}
}

View file

@ -0,0 +1,87 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import edu.cornell.mannlib.vitro.webapp.beans.ApplicationBean;
import edu.cornell.mannlib.vitro.webapp.beans.Portal;
import edu.cornell.mannlib.vitro.webapp.controller.ContactMailServlet;
/**
* Controller for comments ("contact us") page
* * @author bjl23
*/
public class UserMailController extends VitroHttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
public void doGet( HttpServletRequest request, HttpServletResponse response )
throws IOException, ServletException {
super.doGet(request,response);
VitroRequest vreq = new VitroRequest(request);
try {
//this try block passes any errors to error.jsp
if (!ContactMailServlet.isSmtpHostConfigured()) {
request.setAttribute("title", "Mail All Users Form");
request.setAttribute("bodyJsp", "/contact_err.jsp");// <<< this is where the body gets set
request.setAttribute("ERR","This application has not yet been configured to send mail -- " +
"smtp host has not been specified in the configuration properties file.");
RequestDispatcher errd = request.getRequestDispatcher(Controllers.BASIC_JSP);
errd.forward(request, response);
}
ApplicationBean appBean=vreq.getAppBean();
Portal portalBean=vreq.getPortal();
if ( (appBean.getMaxSharedPortalId()-appBean.getMinSharedPortalId()) > 1
&& ( (portalBean.getPortalId() >= appBean.getMinSharedPortalId()
&& portalBean.getPortalId() <= appBean.getMaxSharedPortalId() )
|| portalBean.getPortalId() == appBean.getSharedPortalFlagNumeric() )
) {
request.setAttribute("portalType","CALSResearch");
} else
if (portalBean.getAppName().equalsIgnoreCase("CALS Impact")){
request.setAttribute("portalType", "CALSImpact");
} else if (portalBean.getAppName().equalsIgnoreCase("VIVO")) {
request.setAttribute("portalType", "VIVO");
} else {
request.setAttribute("portalType", "clone");
}
request.setAttribute("siteName",portalBean.getAppName());
request.setAttribute("scripts","/js/commentsForm.js");
if (request.getHeader("Referer") == null)
request.getSession().setAttribute("commentsFormReferer","none");
else
request.getSession().setAttribute("commentsFormReferer",request.getHeader("Referer"));
request.setAttribute("portalId",Integer.valueOf(portalBean.getPortalId()));
request.setAttribute("title", portalBean.getAppName()+" Mail Users Form");
request.setAttribute("bodyJsp", "/emailUsers.jsp");// <<< this is where the body gets set
request.setAttribute("portalBean",portalBean);
RequestDispatcher rd =
request.getRequestDispatcher(Controllers.BASIC_JSP);
rd.forward(request, response);
} catch (Throwable e) {
// This is how we use an error.jsp
//it expects javax.servlet.jsp.jspException to be set to the
//exception so that it can display the info out of that.
request.setAttribute("javax.servlet.jsp.jspException", e);
RequestDispatcher rd = request.getRequestDispatcher("/error.jsp");
rd.include(request, response);
}
}
}

View file

@ -21,4 +21,6 @@ public interface UserDao {
public void deleteUser(User user);
public List<String> getIndividualsUserMayEditAs(String userURI);
public List<String> getUserAccountEmails();
}

View file

@ -54,5 +54,9 @@ public class UserDaoFiltering extends BaseFiltering implements UserDao{
public List<String> getIndividualsUserMayEditAs(String userURI) {
return innerDao.getIndividualsUserMayEditAs(userURI);
}
public List<String> getUserAccountEmails() {
return innerDao.getUserAccountEmails();
}
}

View file

@ -40,6 +40,8 @@ public class UserDaoJena extends JenaBaseDao implements UserDao {
return getOntModelSelector().getUserAccountsModel();
}
public List<User> getAllUsers() {
List<User> allUsersList = new ArrayList<User>();
getOntModel().enterCriticalSection(Lock.READ);
@ -229,4 +231,59 @@ public class UserDaoJena extends JenaBaseDao implements UserDao {
return uris;
}
//Method to get all user accounts that are associated with a person where said person has email address
public List<String> getUserAccountEmails() {
List<String> email = new ArrayList<String>();
List<String> uris = new ArrayList<String>();
OntModel ontModel = getOntModel();
OntModel baseModel = getOntModelSelector().getFullModel();
ontModel.enterCriticalSection(Lock.READ);
String swrcOntology = "http://swrc.ontoware.org/ontology#";
String emailProperty = swrcOntology + "email";
String emailValue, uri;
System.out.println("To clarify here is may edit as " + VitroVocabulary.MAY_EDIT_AS);
try{
Property emailProp = ontModel.getProperty(emailProperty);
StmtIterator it = ontModel.listStatements(
null,
ontModel.getProperty(VitroVocabulary.MAY_EDIT_AS),
(RDFNode)null);
while(it.hasNext()){
try{
Statement stmt = (Statement) it.next();
if( stmt != null && stmt.getObject()!= null
&& stmt.getObject().asNode() != null
&& stmt.getObject().asNode().getURI() != null )
{
uri = stmt.getObject().asNode().getURI();
System.out.println("Returned URI is " + uri);
StmtIterator emailIt = baseModel.listStatements(baseModel.createResource(uri), baseModel.createProperty(emailProperty), (RDFNode) null);
System.out.println("Email iterator successfull ? " + emailIt.hasNext());
while(emailIt.hasNext()) {
Statement emailSt = (Statement) emailIt.next();
if(emailSt != null && emailSt.getObject().isLiteral() && emailSt.getObject() != null) {
email.add(emailSt.getLiteral().getString());
//Issue: this prints out the email in a tags
System.out.println("Email Iterator Object Value" + emailSt.getLiteral().getString());
} else {
//System.out.println("Unfortunately email statement is null");
}
}
}
}catch(Exception ex){
log.debug("error in get User Account Emails()",ex);
}
}
}finally{
ontModel.leaveCriticalSection();
}
return email;
}
}