base.jee.api.cassandra.SendEmail Maven / Gradle / Ivy
/**
* Creative commons Attribution-NonCommercial license.
*
* http://creativecommons.org/licenses/by-nc/2.5/au/deed.en_GB
*
* NO WARRANTY IS GIVEN OR IMPLIED, USE AT YOUR OWN RISK.
*/
package base.jee.api.cassandra;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import java.util.Map;
import base.Command;
import base.jee.api.model.Email;
import base.security.User;
import base.uuid.UUID;
import com.datastax.driver.core.Session;
import static base.jee.api.cassandra.util.Log.log;
/**
* Send an email. Email is not immediately sent, but stored in an email delivery queue.
*/
public class SendEmail extends Command {
private CassandraAPI api;
private User user;
private Email email;
public SendEmail(CassandraAPI api, User user, String email) throws IOException {
if(api == null) {
throw new IllegalArgumentException("Invalid parameter: api");
}
if(user == null || !user.isAuthenticated()) {
throw new IllegalArgumentException("Requires an authenticated user.");
}
if(email == null || email.length() == 0) {
throw new IllegalArgumentException("Invalid parameter: email");
}
this.api = api;
this.user = user;
this.email = new Email(email);
}
@Override
public Command newWithParameters(Map parameters) throws IOException {
return new SendEmail(
(CassandraAPI)parameters.get("api"),
(User)parameters.get("user"),
(String)parameters.get("email"));
}
@Override
protected void execute() throws IOException {
Connection c = null;
PreparedStatement s = null;
Session sn = api.getCassandraSession();
try {
c = api.getDataSource().getConnection();
c.setAutoCommit(false);
if(!user.isAuthenticated()) {
c.rollback();
log(sn, "WARN", user, "Permission denied invoking: " + SendEmail.class.getSimpleName() + " " + getJsonParameters());
c.commit();
throw new IllegalStateException("You do not have permission to send email.");
}
s = c.prepareStatement("insert into email (uuid,to_address,email,retries,attempt_at,in_progress) values(?,?,?,0,?,0)");
s.setString(1, new UUID().toString());
s.setString(2, email.getTo());
s.setString(3, email.toJson());
s.setLong(4, new Date().getTime());
s.execute();
s.close();
s = null;
c.commit();
c.close();
c = null;
} catch(SQLException e) {
throw new IOException(e);
} finally {
if(s != null) { try { s.close(); } catch(SQLException e) {} }
if(c != null) {
try { c.rollback(); } catch (SQLException e) { }
try { c.close(); } catch (SQLException e) { }
}
}
}
@Override
public String getJsonParameters() {
return "{" +
"\"person\":" + user.getPersonUuid() + "" +
"}";
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy