/*
Copyright (C) 2010 maik.jablonski@gmail.com
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package jfix.mail;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.LineNumberReader;
import java.io.OutputStream;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.commons.mail.Email;
public class MailDropHost extends MailHost {
public static String DEFAULT_SPOOL_DIRECTORY = "/tmp/maildrop/spool"
.replace("/", File.separator);
private String uuid;
private String spoolDirectory;
private List<File> spooledMails;
public MailDropHost() {
this(DEFAULT_SPOOL_DIRECTORY);
}
public MailDropHost(String spoolDirectory) {
new File(spoolDirectory).mkdirs();
this.spoolDirectory = spoolDirectory;
reset();
}
private void reset() {
uuid = UUID.randomUUID().toString() + "-";
spooledMails = new ArrayList<File>();
}
public void commit() {
for (File file : spooledMails) {
file.renameTo(new File(file.getAbsolutePath().replace(".lck", "")));
}
reset();
}
public void rollback() {
for (File file : spooledMails) {
file.delete();
}
reset();
}
public void send(Email email) throws Exception {
OutputStream out = newOutputStream();
write(email, out);
out.close();
}
public void send(String returnpath, String recipients, byte[] msg)
throws Exception {
OutputStream out = newOutputStream();
write(returnpath, recipients, msg, out);
out.close();
}
public void stream(Reader reader) throws Exception {
LineNumberReader lineNumberReader = new LineNumberReader(reader);
OutputStream out = null;
for (String line; (line = lineNumberReader.readLine()) != null;) {
if (line.startsWith("##To:")) {
if (out != null) {
out.close();
}
out = newOutputStream();
}
out.write(line.getBytes());
out.write('\n');
}
if (out != null) {
out.close();
}
}
private OutputStream newOutputStream() throws Exception {
File spooledMail = File.createTempFile(uuid, ".lck", new File(
spoolDirectory));
spooledMails.add(spooledMail);
OutputStream out = new BufferedOutputStream(new FileOutputStream(
spooledMail));
return out;
}
}