1 package org.campware.cream.modules.scheduledjobs; 2 3 42 43 import java.util.Date ; 45 import java.text.SimpleDateFormat ; 46 import java.text.DateFormat ; 47 import java.text.ParsePosition ; 48 import java.util.*; 49 import java.text.ParseException ; 50 import java.lang.System ; 51 import java.io.*; 52 import java.util.Properties ; 53 import javax.mail.*; 54 import javax.mail.internet.*; 55 56 import org.apache.turbine.Turbine; 58 import org.apache.turbine.modules.ScheduledJob; 59 import org.apache.turbine.services.schedule.JobEntry; 60 import org.apache.commons.logging.Log; 61 import org.apache.commons.logging.LogFactory; 62 63 import org.apache.torque.util.Criteria; 64 import org.apache.torque.util.Transaction; 65 import java.sql.Connection ; 66 67 import org.campware.cream.om.InboxEvent; 68 import org.campware.cream.om.InboxEventPeer; 69 import org.campware.cream.om.InboxAttachment; 70 import org.campware.cream.om.Customer; 71 import org.campware.cream.om.CustomerPeer; 72 import org.campware.cream.modules.util.Base64; 73 import java.net.URLEncoder ; 74 75 81 public class Pop3Job extends ScheduledJob 82 { 83 84 private static Log log = LogFactory.getLog(Pop3Job.class); 85 86 private int taskcount = 0; 87 88 91 public Pop3Job() 92 { 93 } 95 96 97 103 public void run( JobEntry job ) throws Exception 104 { 105 doReceiveMessages(); 107 } 108 109 110 private void doReceiveMessages() throws Exception { 111 112 113 log.debug("Checking mail "); 114 115 String host = Turbine.getConfiguration().getString("mail.pop3.host"); 116 String username = Turbine.getConfiguration().getString("mail.pop3.user"); 117 String password = Turbine.getConfiguration().getString("mail.pop3.password"); 118 119 Properties props = new Properties (); 121 122 Session session = Session.getDefaultInstance(props, null); 124 125 Store store = session.getStore("pop3"); 127 128 store.connect(host, username, password); 130 131 Folder folder = store.getFolder("INBOX"); 133 134 folder.open(Folder.READ_WRITE); 136 137 Message[] messages = folder.getMessages(); 140 FetchProfile fp = new FetchProfile(); 141 fp.add(FetchProfile.Item.ENVELOPE); 142 fp.add(FetchProfile.Item.FLAGS); 143 fp.add("X-Mailer"); 144 folder.fetch(messages, fp); 145 146 for (int i = 0; i < messages.length; i++) { 147 148 log.debug("Retrieving message "+i); 149 150 InboxEvent entry = new InboxEvent(); 153 Address fromAddress= new InternetAddress(); 154 String from= new String (); 155 String name= new String (); 156 String email= new String (); 157 String replyTo= new String (); 158 String subject= new String (); 159 String content= new String (); 160 Date sentDate= new Date (); 161 int emailformat= 10; 162 163 Message m = messages[i]; 164 165 Object o = m.getContent(); 167 168 if (m.isMimeType("text/plain")) { 170 content = "<PRE style=\"font-size: 12px;\">" + (String )o + "</PRE>"; 171 emailformat=10; 172 } else if (m.isMimeType("text/html")) { 173 content = (String )o; 174 emailformat=20; 175 } else if (m.isMimeType("text/*")) { 176 content = (String )o; 177 emailformat=30; 178 } else if (m.isMimeType("multipart/alternative")) { 179 try { 180 content = handleAlternative(o, content); 181 emailformat=20; 182 } 183 catch (Exception ex) { 184 content="Problem with the message format. Messssage has left on the email server."; 185 emailformat=50; 186 log.error(ex.getMessage(),ex); 187 } 188 } else if (m.isMimeType("multipart/*")) { 189 try { 190 content = handleMulitipart(o, content, entry); 191 emailformat=40; 192 } 193 catch (Exception ex) { 194 content="Problem with the message format. Messssage has left on the email server."; 195 emailformat=50; 196 log.error(ex.getMessage(),ex); 197 } 198 } else { 199 content="Problem with the message format. Messssage has left on the email server."; 200 emailformat=50; 201 log.debug("Could not handle properly"); 202 } 203 204 email= ((InternetAddress)m.getFrom()[0]).getAddress(); 205 name= ((InternetAddress)m.getFrom()[0]).getPersonal(); 206 replyTo= ((InternetAddress)m.getReplyTo()[0]).getAddress(); 207 sentDate= m.getSentDate(); 208 subject= m.getSubject(); 209 210 log.debug("Got message "+email+" "+name+" "+subject+" "+content); 211 212 213 Criteria criteria = new Criteria(); 215 criteria.add(CustomerPeer.EMAIL, (Object )email, Criteria.EQUAL); 216 if (CustomerPeer.doSelect(criteria).size()>0){ 217 log.debug("From known customer"); 218 Customer myDistrib = (Customer) CustomerPeer.doSelect(criteria).get(0); 219 entry.setCustomerId(myDistrib.getCustomerId()); 220 } 221 222 entry.setInboxEventCode(getTempCode()); 223 entry.setEventType(10); 224 entry.setEventChannel(10); 225 entry.setEmailFormat(emailformat); 226 entry.setSubject(subject); 227 entry.setSenderEmail(email); 228 entry.setSenderName(name); 229 entry.setSenderReplyTo(replyTo); 230 entry.setSentTime(sentDate); 231 entry.setBody(content); 232 entry.setIssuedDate(new Date ()); 233 entry.setCreatedBy("system"); 234 entry.setCreated(new Date ()); 235 entry.setModifiedBy("system"); 236 entry.setModified(new Date ()); 237 238 Connection conn = Transaction.begin(InboxEventPeer.DATABASE_NAME); 239 boolean success = false; 240 try { 241 entry.save(conn); 242 entry.setInboxEventCode(getRowCode("IE", entry.getInboxEventId())); 243 entry.save(conn); 244 Transaction.commit(conn); 245 success = true; 246 } finally { 247 log.debug("Succcessfully stored in db: "+success); 248 if (!success) Transaction.safeRollback(conn); 249 } 250 251 if (emailformat!=50){ 252 m.setFlag(Flags.Flag.DELETED, true); 253 } 254 } 255 256 folder.close(true); 258 store.close(); 259 260 } 261 262 private String handleAlternative(Object o, String content) throws Exception { 263 264 Multipart multipart = (Multipart) o; 265 for (int k=0, n=multipart.getCount(); k<n; k++) { 266 Part part = multipart.getBodyPart(k); 267 MimeBodyPart mbp = (MimeBodyPart)part; 268 269 if (mbp.isMimeType("text/html")) { 270 log.debug("---------------> Handle html alternative. "); 271 content += (String )part.getContent(); 272 } 273 274 } 275 276 return content; 277 } 278 279 private String handleMulitipart(Object o, String content, InboxEvent inboxentry) throws Exception { 280 281 Multipart multipart = (Multipart) o; 282 283 for (int k=0, n=multipart.getCount(); k<n; k++) { 284 285 Part part = multipart.getBodyPart(k); 286 String disposition = part.getDisposition(); 287 MimeBodyPart mbp = (MimeBodyPart)part; 288 289 if ((disposition != null) && (disposition.equals(Part.ATTACHMENT))){ 290 log.debug("---------------> Saving File "+part.getFileName()+" "+part.getContent()); 291 saveAttachment(part, inboxentry); 292 293 }else{ 294 if (mbp.isMimeType("text/plain")) { 296 log.debug("---------------> Handle plain. "); 297 content += "<PRE style=\"font-size: 12px;\">" + (String )part.getContent() + "</PRE>"; 298 } else if (mbp.isMimeType("text/html")) { 300 log.debug("---------------> Handle plain. "); 301 content += (String )part.getContent(); 302 } else { 303 log.debug("---------------> Special non-attachment cases "+" "+part.getContentType()); 306 if ( mbp.isMimeType("multipart/*") ){ 307 Object ob = part.getContent(); 308 content = this.handleMulitipart(ob, content, inboxentry)+ "\n\n" + content; 309 }else{ 310 saveAttachment(part, inboxentry); 311 } 312 } 313 } 314 } 315 316 return content; 317 } 318 319 private void saveAttachment(Part part, InboxEvent inboxentry) throws Exception { 320 321 MimeBodyPart mbp = (MimeBodyPart)part; 322 String fileName= mbp.getFileName(); 323 String fileType= mbp.getContentType(); 324 String fileId= mbp.getContentID(); 325 String fileEncoding= mbp.getEncoding(); 326 String attContent; 327 328 if (fileName==null || fileName.length()<2){ 329 fileName= new String ("Unknown"); 330 if (fileType.indexOf("name")>0){ 331 int i = fileType.indexOf("name"); 332 int j = fileType.indexOf("\"", i+1); 333 if (j!=-1){ 334 int k = fileType.indexOf("\"", j+1); 335 if (k!=-1){ 336 fileName= fileType.substring(j+1, k); 337 } 338 339 } else { 340 int k = fileType.indexOf(";", i+1); 341 if (k!=-1){ 342 fileName= fileType.substring(i+5, k); 343 344 }else{ 345 fileName= fileType.substring(i+5, fileType.length()); 346 } 347 348 } 349 } 350 } 351 352 InboxAttachment entryItem= new InboxAttachment(); 353 354 entryItem.setFileName(fileName); 355 if (fileType!=null) entryItem.setContentType(fileType); 356 357 if (mbp.getContent() instanceof InputStream){ 358 InputStream is = new Base64.InputStream(mbp.getInputStream(), Base64.ENCODE); 359 360 BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 361 362 StringBuffer att = new StringBuffer (); 363 String thisLine=reader.readLine(); 364 365 while (thisLine!=null) { 366 att.append(thisLine); 367 thisLine=reader.readLine(); 368 } 369 370 attContent= att.toString(); 371 374 }else{ 375 attContent = part.getContent().toString() ; 376 } 377 378 379 entryItem.setContent(attContent); 380 entryItem.setContentId(fileId); 381 382 inboxentry.addInboxAttachment(entryItem); 383 384 } 385 386 private String saveFile(String filename,InputStream stream){ 387 388 String pf = this.getClass().getResource("Pop3Job.class").getPath(); 389 pf = pf.substring(0, pf.indexOf("/cream")); 390 String attachments_url = "/cream/attachments/"; String attachments_fs = pf+attachments_url; attachments_fs = java.net.URLDecoder.decode(attachments_fs); 393 394 395 String url = ""; 396 File file = new File(attachments_fs+filename); 397 398 for (int i=0; file.exists(); i++) { 399 file = new File(attachments_fs+i+filename); 400 filename = i+filename; 401 } 402 403 try { 404 file.createNewFile(); 405 } catch (IOException ex1) { 406 ex1.printStackTrace(); 407 return ""; 408 } 409 410 log.debug("----- FILE CREATED "+file.exists()+" "+file.getAbsolutePath()+" "+file.canWrite()); 411 412 url = "<a HREF='"+attachments_url+filename+"' target='_blank'>"+filename+"</a><br>"; 413 414 try { 415 FileOutputStream FOS = new FileOutputStream(file); 416 417 byte b[] = new byte[16 * 1024]; 418 for (; ; ) { 419 int bytes = stream.read(b); 420 if (bytes < 0) { 421 break; 422 } 423 if (bytes > 0) { 424 FOS.write(b, 0, bytes); 425 } 426 } 427 FOS.close(); 428 stream.close(); 429 } catch (Exception ex) { 430 ex.printStackTrace(); 431 return ""; 432 } 433 434 return url; 435 } 436 437 438 private String getTempCode() 439 { 440 Date currDate= new Date (); 441 return Integer.toString(currDate.hashCode()); 442 } 443 444 private String getRowCode(String s, int i) 445 { 446 String is= new String (); 447 448 is= Integer.toString(i); 449 while (is.length()<7) 450 { 451 is="0" + is; 452 } 453 454 is= s + is; 455 return is; 456 } 457 458 private String formatDate(Date d) 459 { 460 SimpleDateFormat formatter = new SimpleDateFormat ("dd.MM.yyyy"); 461 return formatter.format(d); 462 } 463 464 465 } 466 | Popular Tags |