1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
| package com.thales.sat.lsr.pratic.mail.impl;
import static junit.framework.Assert.assertTrue;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.thales.sat.lsr.pratic.common.BeanWithProperties;
import com.thales.sat.lsr.pratic.mail.MailException;
import com.thales.sat.lsr.pratic.mail.MailManager;
//RPE le 2008/09/30 : sauvegarde des tickets com dans le répertoire inscrit dans la base de registre HKCU/Software/JavaSoft/Prefs, clé pathticketcom
import java.util.prefs.Preferences; //fin RPE
public class MailManagerImpl extends BeanWithProperties
implements MailManager{
private static Log log =LogFactory.getLog(MailManagerImpl.class);
// clé de la propriété du répertoire de sortie
public final String PROP_OUTPUTDIR = "mail.manager.output.directory";
// valeur par defaut du répertoire de sortie
public final String VALUE_OUTPUTDIR = "D:/NMC/utilisateur/mesure/ticket_com";
// clé de la propriété de suppression des mails
public final String PROP_DELETE = "mail.manager.delete.message";
// valeur par defaut de la suppression des mails
public final String VALUE_DELETE = "true";
// clé de la propriété d'ecrasement des mails
public final String PROP_OVERWRITE = "mail.manager.overwrite.message";
// valeur par defaut d'ecrasement des mails
public final String VALUE_OVERWRITE = "true";
// Format des dates pour l'arborescence de sauvegarde
public final SimpleDateFormat DATEFORMAT =
new SimpleDateFormat("yyyyMMdd_HHmmss");
// Renvoie un Id unique pour chaque mail du type : sender@domain_date
String getId(Message message) throws MessagingException{
return message.getReplyTo()[0].toString() + "_" +
DATEFORMAT.format(message.getSentDate());
}
/**
* Méthode principale du traitement. Le processus est le suivant :<br>
* - Connexion au serveur Mail<br>
* - Pour chacun des répertoires <br>
* - Recupération des messages<br>
* - Sauvegarde des pieces jointes<br>
* - Suppression des messages<br>
*
*/
public void process() throws MailException {
Store store = null;
try{
boolean overwrite = getBooleanProperty(PROP_OVERWRITE,VALUE_OVERWRITE);
boolean delete = getBooleanProperty(PROP_DELETE,VALUE_DELETE);
store = session.getStore();
store.connect();
Folder folder = store.getDefaultFolder();
Folder[] folders = folder.list();
for(Folder f : folders){
log.info( "Checking Mail Folder : " + f.getFullName());
f.open(Folder.READ_WRITE);
for(Message message : f.getMessages()){
String id = getId(message) ;
log.info( "Loading message : " + id );
// RPE le 2008/09/30 : sauvegarde des tickets com dans le répertoire inscrit dans la base de registre HKCU/Software/JavaSoft/Prefs, clé pathticketcom
//String directory = getProperty(PROP_OUTPUTDIR, VALUE_OUTPUTDIR) + "/" + id;
Preferences p = Preferences.userRoot();
String directory = p.get("pathticketcom", "erreur d'acces") + "/" + id;
// fin RPE
log.debug(message.getFrom()[0].toString() + " : " + message.getSubject() + " dumped to " + directory);
File dir = new File(directory);
if( dir.exists() ){
log.warn("Directory already exists : " + dir.getAbsolutePath());
if( overwrite == false ){
continue;
}
}else{
assertTrue("Unable to create " + directory, dir.mkdirs());
}
Object content = message.getContent();
if (content instanceof Multipart) {
handleMultipart((Multipart)content,directory);
} else {
handlePart(message,directory);
}
message.setFlag(Flags.Flag.DELETED, delete);
}
f.close(true);
}
}catch(Exception e){
throw new MailException(e);
}finally{
if( store != null &&
store.isConnected() ){
try { store.close(); } catch (MessagingException e) {}
}
}
}
// Session mail utilisée
Session session;
public Session getSession() {
return session;
}
public void setSession(Session session) {
this.session = session;
}
/**
* Decompose chaque partie du mail et sauvegarde les fichiers joints
* dans le repertoire <tt>dir</tt>
* @param multipart : differentes parties du mail
* @param dir : repertoire ou doivent etre stockes les pieces jointes
* @throws MessagingException
* @throws IOException
*/
private void handleMultipart(Multipart multipart,String dir)
throws MessagingException, IOException {
for (int i=0, n=multipart.getCount(); i<n; i++) {
handlePart(multipart.getBodyPart(i),dir);
}
}
/**
* extrait la piece jointe de <tt>part</tt> et la sauvegarde
* dans le repertoire <tt>dir</tt>
* @param multipart : differentes parties du mail
* @param dir : repertoire ou doit etre stockes la piece jointe
* @throws MessagingException
* @throws IOException
*/
public void handlePart(Part part,String dir)
throws MessagingException, IOException {
String disposition = part.getDisposition();
String contentType = part.getContentType();
if (disposition == null) { // When just body
part.writeTo(System.out);
} else if (disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
log.debug("Attachment: " + part.getFileName() + " : " + contentType);
String name = part.getFileName();
if( name == null ){
name = "UNKNOWN_FILE.txt";
}
saveFile(dir + "/" + name , part.getInputStream());
} else {
log.warn("Part Type unexpected : " + disposition);
}
}
/**
* Sauvegarde le flux dans le fichier indiqué
* @param filename
* @param input
* @throws IOException
*/
private void saveFile(String filename, InputStream input) throws IOException {
boolean overwrite = getBooleanProperty(PROP_OVERWRITE,VALUE_OVERWRITE);
File file = new File(filename);
if( file.exists() ){
if( overwrite ){
file.delete();
}else{
log.warn("File has already been saved : " + filename);
return;
}
}
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
BufferedInputStream bis = new BufferedInputStream(input);
int aByte;
while ((aByte = bis.read()) != -1) {
bos.write(aByte);
}
bos.flush();
bos.close();
bis.close();
}
} |
Partager